我有一个相当简单的问题(除了我)...我创建了一个牌手阵列,我想按照hierchy中出现的顺序通过数组访问他们的名字:
例如,在层次结构中显示:
Canvas
Hand
card1
card2
card3
card4
我创建了这段代码:
players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject go in players)
{
Debug.Log("Player " + go + " is named " + go.name);
}
我可以访问卡片手,但顺序错误。有什么建议吗?
由于
马龙
答案 0 :(得分:2)
永远不要依赖于项FindGameObjectsWithTag
返回的顺序,因为这未在文档中指定,并且可能无法预测。您必须添加循环遍历数组的自定义函数,并通过与GameObject.name
属性进行比较来查找指定的GameObject。
GameObject[] players;
void test()
{
players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject go in players)
{
Debug.Log("Player " + go + " is named " + go.name);
}
}
GameObject getGameObject(string gameObjectName)
{
for (int i = 0; i < players.Length; i++)
{
//Return GameObject if the name Matches
if (players[i].name == gameObjectName)
{
return players[i];
}
}
Debug.Log("No GameObject with the name \"" + gameObjectName + "\" found in the array");
//No Match found, return null
return null;
}
<强>用法强>:
GameObject card1 = getGameObject("card1");
GameObject card2 = getGameObject("card2");
GameObject card3 = getGameObject("card3");
GameObject card4 = getGameObject("card4");
修改强>:
如果你的目标是按顺序对数组中的项进行排序,那么应该这样做:
players = GameObject.FindGameObjectsWithTag("Player");
players = players.OrderBy(c => c.name).ToArray();