Camilo Terevinto
Camilo Terevinto

Reputation: 32068

Move UI component after it was instantiated

I am creating a 3D game which is going to be a strategy game. I want to create a panel (UI group of a bunch of texts and buttons) by code (C#) and then move them so they are on top of a GameObject in the Canvas layout. So I am doing this:

 if (ThisBuilding == null)
     ThisBuilding = this.gameObject;
 Panel = Canvas.Instantiate(Panel);
 Panel.transform.SetParent(canvas.transform, false); //false to prevent stupid scaling issues created by the parent change

 Vector3 centerPosition = ThisBuilding.GetComponentInChildren<MeshRenderer>().bounds.center; //the building GameObject contains a MeshRenderer component in its only children.
 panelRect.anchoredPosition = Vector3.Lerp(panelRect.anchoredPosition, centerPosition, 1.0f);

The thing is that this script is run (on Start()) once per building, hoping that the panel would get instantiated 3 times and each panel corresponds to a building, but for some strange reason this does not work.
EXPECTED RESULT: each time the panel gets instantiated, the position is the same as of the building that instantiated it (the building GameObject holds the script and activates / deactivates the panel)
ACTUAL RESULT: even though the panel does get instantiated 3 times as it should, they are all in the same position and do not change even when my Update() function changes its position. What am I doing wrong?

Upvotes: 0

Views: 347

Answers (1)

Jayson Ash
Jayson Ash

Reputation: 709

Giving the world position of the buildings results in the panels being positioned basically in the same location on screen. What is needed is to calculate the world position to the screen position and use the calculated screen position to place the panels.

Try something like this:

panel.transform.position = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);

Upvotes: 2

Related Questions