Search Unity

Unity UI [SOLVED] Trouble moving UI elements with transform.position

Discussion in 'UGUI & TextMesh Pro' started by GeorgeCH, Apr 9, 2017.

  1. GeorgeCH


    Oct 5, 2016
    I confess - I am defeated by the UI.

    What I'm trying to achieve is a simple result where the position of a UI object - a panel - changes from Point A to Point B when the mouse is clicked.

    Specifically, the panelToShow game object should assume / retain a position of 0,0,0 in relation to its parent, while gameobjects in the panelsToHide array all need to be moved off the screen.

    The second part - moving the objects to be hidden off the screen - works flawlessly, but the first part is what's giving me trouble. Concretely, instead of panelToShow having a position of 0,0,0, the panel gets moved not to something completely different (364.5, 243).

    Here's the script attached to the button:

    Code (CSharp):
    1. public class ShowPanel : MonoBehaviour {
    3.     public GameObject panelToShow; // the panel that should be shown to the user
    4.     public GameObject[] panelsToHide = new GameObject[2]; // all the other panels that needs to be hidden
    5.     public Transform parentTransform; // the transform position of the parent (a panel) that I want visible panels to be identical to
    7.     public void PanelShow() // this is what happens when the user clicks the button
    8.         {
    9.         panelToShow.transform.SetParent(parentTransform); // I set the parent of the object to be shown, just to be sure
    10.         panelToShow.transform.localPosition = parentTransform.position; // I attempt to set the position of the panel to be shown to be identical to its parent
    12.         for (int i = 0; i < panelsToHide.Length; i++) // I then loop through the array of the objects to be hidden and move them away from the screen
    13.             {
    14.             panelsToHide[i].transform.SetParent(parentTransform);
    15.             Debug.Log(panelsToHide[i].transform.parent);
    16.             panelsToHide[i].transform.position = new Vector3(1000, 1000, 0);
    17.             }
    18.         }
    19. }
    Why is this happening and how do I set the position of the panel to be shown to be identical to the position of its parent panel (which intentionally doesn't have a sprite attached to it so it doesn't get in the way?
    Last edited: Apr 9, 2017
  2. GeorgeCH


    Oct 5, 2016
    Solved! Turns out, the positioning of the parent object wasn't centered, resulting in some weird results. Explicitly spelling out the new position as new Vector2 (parent.transform.position.x + 100) also helped.
    MasterDataBase and Crycore93 like this.