This tutorial will demonstrate how to program an enemy that follows the player in Unity 3D using C#. This will also cover how to set up the Unity 3D environment, as well as common practices when writing scripts.
-
Create a new Unity project using the Universal 3D pipeline and name it "EnemyThatFollowsPlayerTut".
-
Once the Unity project has loaded, start by creating a terrain for our game objects to be on as we will be adding gravity to our game objects through rigidbody components.
From here we can also create a 3D capsule that we will use as our player in this scene. Once the capsule game object is created, change the value of it's Y position to 0 in the inspector on the right.
Rename the capsule to "player" by right clicking the capsule in the hierarchy and renaming it and then move the terrain so that it is centred on the player and then create another capsule called "Enemy" and move it away from the Player.
-
Right click in an empty space in the assets window at the bottom and create a new MonoBehaviour Script and name it "enemyFollow". Once it is created, open the script in to Visual Code or Visual Studio Code.
-
We can delete the start method as we will not be using it in this script and it is also good practice to not have unused methods in your code, making it neater and easier for others to read.
-
Next, we shall define our variables. We will need a float variable to store our enemies speed and a transform to store our targets position, rotation and scale. See syntax below.
-
Once you have defined your variables, we will simply be using one line of code in the update method to change the position of our enemy in accordance to the position of the target (player). We are doing this in the update method so that our enemy is constantly moving towards our player. See syntax below.
Vector3.MoveTowards calculates the position between the two points we have specified which are: transform.position (position of the enemy) and target.position (position of the player or target) moving no further than the distance that we have specified in our enemySpeed variable multiplied by Time.DeltaTime. This then returns the new position which is our transform.position and the function repeats again as it is inside of the update method.







