How to set up chasing enemies without using navmesh in Unity

Let’s go over a basic implementation of a chasing enemy without using the navmesh system in Unity.

The player controls and shooting were set up in these two articles: one and two.

First, create the IDamageable interface which will be used to damage the enemy and the player:

Create the enemy object and add a CharacterController. Also create a script called Enemy and attach to the object:

Create a sphere and add as a child of the enemy. Remove the mesh renderer and adjust the size of the collider. Set the sphere collider to isTrigger(this collider will be used to detected if player is within damage distance)

Open the enemy script and add the interface:

Create a public enum for the three states the enemy can be in.

Also add:
- Transform for the target to move towards
- CharacterController for the CC on this object
- float for the movement speed
- float for the rotation speed
- int for the maximum health of the enemy
- two floats to handle the attack delay
- the Health property from the interface
- two floats for the gravity

In the Start function set the health to maximum health, set target to the player and initialise the CharacterController:

Create the ChaseTarget function. Normalise the direction to ensure the movement length is always 1 unit and then multiply by movement speed:

Create the FaceTarget function. This will smoothly rotate the enemy towards the player:

Add the Damage function from the interface and also a function to handle the death of the enemy:

Call the functions from the Update function based on the state the enemy is in:

Create a script with a suitable name and attach to the child object of the enemy:

Open up the script. Initialise the enemy in Start. Add two of the OnTrigger functions. Enter will put the enemy in Attack mode and Exit will set the mode back to Chase:

Create a script called Player and attach to the player object. Also set the tag on the player to “Player”:

Open the Player script. Add the IDamageabale interface. Add the property for Health and a float for maximum health. Also add an Action delegate for when the player health has changed. Set the health in the Start function and add the Damage function from the interface:

Good luck!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store