Creating an Enemy That Chases the Player in Unity

Matthew Clark
Nerd For Tech
Published in
3 min readJul 16, 2023

I have implemented player movement in the project I am working on using Unity’s new input system. Now it is time to create an enemy for the player to interact with.

Right-click in the hierarchy and go down to 2D Object -> Sprites -> Circle.

I have chosen to make my enemy red for now by changing the Color in the Inspector.

Now duplicate the enemy sprite and change the Color to black. Change the Scale to 1.1 for x, y, and z. You will also want to change the Order in Layer so that the black sprite is one layer below the red sprite. Now parent the black sprite to the red one to create an outline to make the enemy contrast with the background.

Now create a new script called Enemy and open it. We will be making this an abstract class to utilize class inheritance to be able to make multiple enemy types in the future.

Now create a player game object variable and a speed variable.

Create a virtual method called SetTarget. This method will look for a game object with the player tag. If a game object with the player tag is found it will be set as the player variable. If no player object is found an error will be thrown.

Note: make sure to set the player’s tag to Player in the inspector

We will create an Init virtual method to initialize the SetTarget method. The Init method will be called in the Start method. The Init method will allow us to initialize any future methods or variables needed at the start of a script.

Now create another virtual method called Chase. This method will set the enemy's transform.right to equal the difference between the player's position and the enemy’s position. This will get the direction the enemy needs to move to go toward the player. Then we will update the enemy’s position by adding transform.right multiplied by speed and Time.deltaTime to the enemy’s position.

This will be called in the Update method.

Now create a new script called BasicEnemy that will inherit from the Enemy class.

Attach the BasicEnemy script to the enemy we created.

Now you will have an enemy that will chase the player.

Full Enemy Script

--

--