在层次结构中按名称访问游戏对象的数组/列表
本文关键字:对象 数组 列表 游戏 访问 层次结构 | 更新日期: 2023-09-27 18:14:39
我有一个相当简单的问题(除了我)…我已经创建了一个牌手数组,我想通过一个数组按照层次结构中的顺序访问它们的名字:
例如,在层次结构中显示:
Canvas
Hand
card1
card2
card3
card4
我已经创建了这个代码:
players = GameObject.FindGameObjectsWithTag("Player");
foreach (GameObject go in players)
{
Debug.Log("Player " + go + " is named " + go.name);
}
我可以访问牌手,但顺序是错误的。有什么建议吗?
感谢马龙
永远不要依赖于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();