How to draw and move a crosshair/reticle (2D)?

I want to have a crosshair around my Player at a distance R and angle X. All the old posts I see recommend things like OnGUI and Texture2D but apparently those things are old and deprecated so apparently I need to use Canvas GameObjects on the UI layer.

My setup: a Player class with a public GameObject crosshair field, in which I click+dragged a Canvas I created with GameObject → UI → Image (just a simple gif) named Crosshair. It exists in my Game scene as well.

Here’s the relevant parts of the code:

public GameObject crosshair;
private GameObject reticle;
private void Start () {
    reticle = Instantiate(crosshair, body.position, Quaternion.identity);
}

private void Update() {
    SetAimDirection();
}

private void SetAimDirection() {
    Debug.Log(reticlePosition);
    reticle.transform.position = new Vector3(reticlePosition.x, reticlePosition.y, 0);
}

Despite the Debug.Log reporting real values, the crosshair doesn’t move. Oh and for some reason I get a second Crosshair object (called Crosshair (clone)) when I run the game. What’s the proper way to do this? Should I be using this Canvas/UI layer approach or something else?

Hello there,

If you already have a crosshair in your scene, you don’t need the line in Start(). It creates a new crosshair (which is why you have a (clone) in your scene), and assigns your variable “reticle” to it. Because of that, the function SetAimDirection() updates the position of that clone, instead of your real crosshair.

Here’s a simple Unity tutorial that might help you.

Hope that helps!

Cheers,

~LegendBacon