Wednesday, 8 July 2015

Enemy AI in Unity3D


In this tutorial. we'll add enemy AI in unity3d game by using its built-in navigation system.

I'll assume you're familiar with unity editor and know to perform basic operations like adding game object, attaching script, adding component, etc.

You can access the navigation panel through windows tab on the top.

Follow the steps given below.

  • With navigation panel, check whether your game object is navigation static or not. Walls, floors, platforms, etc should be static.
  • Select all static objects and click on bake in navigation panel.
  • Add a 'nav mesh agent' component to your game object (whom you want to have AI). Tweak with its properties i.e. radius, speed, auto braking, etc as per your requirements.
  • Add the following script to your enemy object.

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour {

public Transform destination;
private NavMeshAgent agent;
void Start () {
agent = gameObject.GetComponent<NavMeshAgent>();


}
void Update () {
agent.SetDestination(destination.position);


}
}

  • Fianlly, set the reference of destination (game object you want your enemy to follow) in unity editor, and you're done.

Facing any issue or got any other question? Comment below and I'll try to answer asap.

No comments:

Post a Comment