Creating a 2D Objective Pointer

Hi Everyone,
I have a sprite of a pointer and i want it to point towards my objective, like in other games, but i cant figure out how, i tried this -

  1. I created a empty game object and made it to look at my objective, i then set the Z rotation of my sprite to Y Rotation of the empty gameobject, it works when the sprite is not attached to the camera, but then i attach it to the camera it gets all messed up.

any help is appreciated.

In simple case:

public class PointRotate : MonoBehaviour
{
    /// <summary> The target objective object that we will be pointing at </summary>
    public GameObject target;

    void Update ()
    {
        // Get the distance (direction) towards the target
        Vector3 distance = target.transform.position - transform.position;
        // Calculate the angle to the target
        float angle = Mathf.Atan2 (distance.x, distance.z) * Mathf.Rad2Deg;
        // Apply our world rotation to match the angle to target (i.e. face it)
        transform.eulerAngles = new Vector3 (0f, angle, 0f);
    }
}

target is whatever GameObject objective you want to point at. This assumes Y axis as “up”.

Edit: Another more intuitive but slower way would be:

gameObject.transform.LookAt (new Vector3(
    target.transform.position.x,
    transform.position.y, // we pretend the target is same level as we
    target.transform.position.z), Vector3.up);