[英]Unity2D: Instantiated Object always at wrong position
我有一個名為“PlayerList”的游戲對象,里面有一個“PlayerListItem”,我將其實例化並克隆到 PlayerList 中,其代碼如下所示:
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);
}
現在我的問題是,克隆的項目總是完全錯誤的 position,而不是我實際實例化它們。 第一項(實際上是第二項,因為我刪除了第一項,因為它是空的)始終具有 X/Y 位置:-420 (x) 和 -573 (y)
奇怪的是在那之后總是使用 -130 y,所以下一項具有與 Y 位置相同的 X Position 和 -703。
看來這是 vector3 function 的問題,因為當我刪除它時,所有項目都只有 0,0 作為 Position。我是否錯誤地使用了 Vector3 Function?
順便說一句,我的游戲對象的矩形變換看起來像這樣:
PlayerListItem 也是 PlayerList 的子項:
感謝任何幫助的人!
在實例化元素后嘗試設置元素的 position。 為 UI 元素設置父級時,將worldPositionStays
設置為 false 也是一個好主意。
var obj = Instantiate(prefab, Root, worldPositionStays: false);
您可能還需要使用position
anchoredPosition
((RectTransform)obj.transform).anchoredPosition = new Vector2(x,y);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.