UI positioning problem

Hi.

In my scene I’m creating some buttons from prefabs on a canvas via script using following code:
<pre> GameObject go = (GameObject)GameObject.Instantiate(cmdButtonPrefab, new Vector3(((i*buttonWithSpacingWidth)) - xAnchorOffset, yOffset), gameObject.transform.rotation); go.transform.SetParent(mnuPanel, false); </pre>

This works fine and shows the same result on all devices and screen resolutions.

If a player now click one of the buttons he get a certain power up and the button is destroyed.
Now the remaining buttons shall reorder so that there is no gap between them. As I don’t want to destroy all buttons and reinstantiate them I simply like to reorder/move the remaining buttons.

Unfortunately I get strange results now. On some devices the buttons overlap, on some there are large gaps between them and I don’t know why.

This is the code I’m using to reorder the buttons:
<pre> RectTransform rectTransform = go.GetComponent(); float xPos = ((Screen.width/2) - (buttonRowWidth / 2)) + (i * buttonWithSpacingWidth) + (buttonWidth/2); rectTransform.position = new Vector3(xPos, go.transform.position.y, go.transform.position.y); </pre>

Any idea what is going wrong?

Common mistake.

You alter and access the UI position with this:

Now go switch all of your code with anchoredPosition and see if there are still problems.