Prefab component not linking to destination

Hy
While trying toimplement my (placeholder) enemy AI. I found that i couldn’t link in my Transform of my player. Also when trying that my enemy prefab would not render properly (no sprite, light stopped working correctly)

If somebody could help that would be appreciated.

public class enemy_behavior : MonoBehaviour
{
    public float speed;
    
    Transform player;
    Rigidbody2D rigidBody;

    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
        rigidBody = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        Vector3 direction = player.transform.position - transform.position;
        transform.rotation = Quaternion.LookRotation(direction);
        rigidBody.AddForce(transform.forward * speed);
    }
}

First, one nitpick, GetCopponent<Transform> is useless, just use .transform


Second, Quaternion.LookRotation doesn’t work like you think it does for 2d. Basically it aligns one axis perfectly to your first argument, and one axis as best it can to your second argument, here the default value of Vector3.up, or the positive y axis.


Bad news for you, but the axis that is aligned to your player’s direction is the local z, or the “depth” axis. So now your enemies are facing your player while standing vertically on your flat world.


To solve this, simply reverse the arguments, Quaternion.LookRotation(Vector3.forward, direction), or Quaternion.LookRotation(-Vector3.forward, direction), can’t remember which. Now you are forcing the forward axis with the world forward axis, so you stay on the plane, but you allow rotation around that axis.