Keeping UI Element To Game Object When Camera Moves

Some background and my problem:

I am making a tower defense game in 2d, and when I click on a tower I have a UI element named “towerPanel” be set to active.

However, when I move the camera, the UI element moves along with the camera as if it were stuck on the lens. I would like the UI element to stick to the tower.

The “towerPanel” is in a canvas, and the canvas is set to “screen space - overlay”

Here is what I am doing:

When clicking on a tower, I get the screen point:

Vector3 screenpos = Camera.main.WorldToScreenPoint(transform.localPosition);

I pass this screenpos to a function that does the following:

private Vector3  screenposition_base_tower_panel;

public void MoveTowerPanel(Vector3 screenPosition_tile)
{
    screenposition_base_tower_panel.x = screenpos.x - 350;
    screenposition_base_tower_panel.y = screenpos.y + 185;

    towerPanel.SetActive(true);
    towerPanel.transform.SetPositionAndRotation(screenposition_base_tower_panel, Quaternion.identity);
}

and the Update function looks like this:

void Update()
{
    if (towerPanel.activeSelf == true)
    {
        towerPanel.transform.position = screenposition_base_tower_panel;
    }
}

and clearly after all of this, the UI element stays to the camera.

Any and all help is appreciated with this.

Hey.

WOWOWO, you are overthinking the problem.

Just need to configure the Render mode of the canvas via inspector, to Worlld position. read the manual. Unity - Manual: Canvas


World Space
This mode renders the UI as if it were a plane object in the scene. Unlike Screen Space - Camera mode, however, the plane need not face the camera and can be oriented however you like. The size of the Canvas can be set using its Rect Transform but its onscreen size will depend on the viewing angle and distance of the camera. Other scene objects can pass behind, through or in front of the Canvas.


You will need that each tower have its own canvas, or make 1 only canvas that moves to tower position when you click it.

So… thank you tormentoarmagedoom. I was DEFINITELY overthinking this.

I got it to work :slight_smile: