C# Unity2D:实例化对象始终位于错误位置
我有一个叫做“PlayerList”的游戏对象,里面有一个“PlayerListItem”,我在PlayerList中实例化并克隆了它,代码如下所示:C# Unity2D:实例化对象始终位于错误位置,c#,visual-studio,unity3d,C#,Visual Studio,Unity3d,我有一个叫做“PlayerList”的游戏对象,里面有一个“PlayerListItem”,我在PlayerList中实例化并克隆了它,代码如下所示: private void CreatePlayerList() { int y = 0; foreach (var player in gameState.PlayerNames) { GameObject PlayerName
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);
}
private void CreatePlayerList()
{
int y=0;
foreach(游戏状态下的var玩家。玩家名称)
{
GameObject PlayerName=实例化(playerListItem,新向量3(0,y),Quaternion.identity,playerList.transform);
PlayerName.getComponentChildren().text=player.FirstName;
playerObject.Add(PlayerName);
y-=130;
if(player.FirstName==gameState.PlayerNames[currentPlayer].FirstName)
{
UpdatePlayerStates();
}
}
//销毁第一个空项
销毁(playerListItem);
}
现在我的问题是,克隆的项目总是位于完全错误的位置,而不是我实际实例化它们。第一个项目(实际上是第二个,因为我删除了第一个项目,因为它是空的)始终具有X/Y位置:-420(X)和-573(Y)
奇怪的是-130y总是在这之后使用,所以下一个项目的X位置和-703位置与y位置相同
这似乎是vector3函数的问题,因为当我删除它时,所有项的位置都是0,0。我是否错误地使用了Vector3函数
顺便说一下,我的游戏对象的矩形变换如下所示:
而且PlayerListItem是PlayerList的孩子:
谢谢你的帮助 实例化元素后,尝试设置元素的位置。为UI元素设置父项时,最好将
worldPositionStays
设置为false
var obj = Instantiate(prefab, Root, worldPositionStays: false);
您可能还需要使用anchoredPosition
而不是position
((RectTransform)obj.transform).anchoredPosition = new Vector2(x,y);
在循环的第二次迭代中。Y是-130。所以是的。除非是第一项。我相信这里的问题是:为什么第二项在
(-420,-573)
,而不是(0,-130)
?确切地说。我希望第二项在0,-130,并且每隔一项在0,y-130,新向量3(0,y)应该是新向量2(0,y)?另外,你可能对孩子和相对位置有问题。你的物体是其他物体的孩子吗?@pseudoabdulvector2做了完全相同的事情。是的,PlayerListItem是PlayerList的孩子,我会更新我最初的帖子!