NakedPython
NakedPython

Reputation: 930

Unity2D: Instantiated Object always at wrong position

I've got an GameObject called "PlayerList" and inside this is a "PlayerListItem", which I Instantiate and clone inside the PlayerList, the code for that looks like this:

private void CreatePlayerList()
        {
            int y = 0;
            foreach (var player in gameState.PlayerNames)
            {
                GameObject PlayerName = Instantiate(playerListItem, new Vector3(0, y), Quaternion.identity, playerList.transform);
                PlayerName.GetComponentInChildren<TMP_Text>().text = player.FirstName;
                PlayerObjects.Add(PlayerName);
                y -= 130;

                if (player.FirstName == gameState.PlayerNames[currentPlayer].FirstName)
                {
                    UpdatePlayerStates();
                }
            }
            // Destroying the first empty item
            Destroy(playerListItem);
        }

Now my problem is, that the cloned items are always at a complete wrong position, than I actually instantiate them. The first item (second actually since I delete the first one because its empty) always has the X/Y Positions: -420 (x) and -573 (y)

The weird thing is that the -130 y is always used after that, so the next item has the same X Position and -703 as Y-Position.

It appears this is a problem of the vector3 function, since when I removed it, all items just had 0,0 as Position. Am I using the Vector3 Function incorrectly?

The Rect Transform of my GameObjects looks like this by the way:

PlayerList

enter image description here

And also the PlayerListItem is a child of the PlayerList:

structure

Thanks for anyone who helps!

Upvotes: 0

Views: 562

Answers (1)

Iggy
Iggy

Reputation: 4888

Try setting the position of the elements after instantiating them. It's also a good idea to set worldPositionStays to false when parenting UI elements.

var obj = Instantiate(prefab, Root, worldPositionStays: false);

You may also need to use anchoredPosition instead of position.

((RectTransform)obj.transform).anchoredPosition = new Vector2(x,y);

Upvotes: 1

Related Questions