How can I make a 2D enemy follow the player?

Hello. I am new to game development . I have successfully added my enemy to the scene but I want the enemy to follow my player. How do I do that?

1 Like

Welcome. I think this script should help. attach it to your enemy. inside there is a reference to the player object so you would need to attach your player to the field via the unity editor. Thanks

using UnityEngine;

public class EnemyFollow : MonoBehaviour
{
    public Transform player;
    public float speed = 2f;

    void Update()
    {
        if (player != null)
        {
            Vector3 direction = (player.position - transform.position).normalized;
            transform.position += direction * speed * Time.deltaTime;
        }
    }
}