Unity3D中FindGameObjectsWithTag的排序问题

版权声明:本文为博主原创文章,未经博主允许不得用于任何商业用途,转载请注明出处。 https://blog.csdn.net/beihuanlihe130/article/details/76216468

在Unity中,当我们的模型结构较为复杂时,通常我们会为某些层级的模型指定相应的Tag,当我们通过FindGameObjectsWithTag来找到我们想要的物体时,他们通常并不是按照在Hierarchy中的顺序来填充我们的数组,而是以一种随机的方式来完成。当我们需要对其进行排序时,可以借助GetSiblingIndex()来实现。
通过GetSiblingIndex()方法来获取该物体在Hierarchy中的层级,通过该参数来对我们的GameObject数组进行排序即可。

using System.Linq;
......
private GameObject[] FindObjectsWithMyTag(string tag)
{
    GameObject[] allColumns = GameObject.FindGameObjectsWithTag(tag).OrderBy(g => g.transform.GetSiblingIndex()).ToArray();
    //var list = new List<GameObject>(GameObject.FindGameObjectsWithTag(tag));
    //list.Sort((e1, e2) => e1.transform.GetSiblingIndex().CompareTo(e2.transform.GetSiblingIndex()));
    //或者通过其他的排序方式来完成。
    return allColumns;
}

猜你喜欢

转载自blog.csdn.net/beihuanlihe130/article/details/76216468