How to make Enemy follow the player in Unity Tutorial

How to make the Enemy Object follow the player.

We got two Objects in the scene. Our Player Object and our enemy Object. Now we want our enemy Object to follow our player Object.

How do we achieve this?

We use the function “LookAt(objectToLookAt)” and transform the position of the Enemy object.

Here is the working script:

using UnityEngine;
public class EnemyFollowPlayer : MonoBehaviour
    public GameObject Player;
    public float movementSpeed = 4;

    void Update()
        transform.position += transform.forward * movementSpeed * Time.deltaTime;

Looks good, but the enemy object stops before the player when we distance ourselves too much.

It looks like our enemy object is too Tall.

If we change the size of it to it 1 x 1 x 1. Everything works perfectly fine.

The reason for it is that we are using Rigidbody element and the vector pointing toward our player is based on the middle of the Box collider.

A quick fix is to set the box collider 0.5 point lower. This way we get our vector of enemy player pointing right in our player direction.

Don’t forget to set the Movement Speed and set our Player Object in the Inspector!

That’s all for Today.

Check other tutorials on this Topic:

Spawning elements in Unity on Button Click

Making the camera follow an Object in Unity3D

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.