Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[SOLVED] Moving a UI button from the left to the right of another UI button

Discussion in 'Scripting' started by Deleted User, Feb 13, 2015.

  1. Deleted User

    Deleted User

    Guest

    I have 2 buttons side by side with a small gap in between them in the editor. I want to move the button on the left to the right of the 2nd button by script and maintain the same small gap.

    The way I do it is like this:
    1) My items are added to the list then I find their distance:
    Code (CSharp):
    1. float distance = Mathf.Abs (Mathf.Abs(items [0].transform.position.x) - Mathf.Abs(items [1].transform.position.x));
    2) I move the first item behind the 2nd one by adding distance to it:
    Code (CSharp):
    1. first.position = new Vector3 (items.LastOrDefault ().transform.position.x + distance, first.position.y, first.position.z);
    But the problem is when I move it, the gap increases a lot. About 3x what it should be. Not sure why that is. I'd like it to keep the same gap as it does in the editor.
     
  2. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    You should use the new UI system which uses RectTransforms. Also, if the buttons are childed to another object, you will want to use local position.
     
  3. Deleted User

    Deleted User

    Guest

    I am using the new UI system. RectTransform inherits from Transform so a GameObject can only either have one Transform or RectTransform attached to it at once.
    All buttons are child of the canvas only. How can I get their local position?
     
  4. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    transform.localPosition
     
    Deleted User likes this.
  5. Deleted User

    Deleted User

    Guest

    Thanks I got it working by replacing every "position" in the OP with "localPosition"
     
    Fluzing likes this.