public void FindClosestEnemy()
{
List<GameObject> pList = GameObject.FindGameObjectsWithTag("Player");
pList.OrderBy(obj=>Vector3.Distance(FindLocalPlayer().transform.position,
obj.transform.position)).ToList();
}
我不明白这两个列表之间的区别。如何将“UnityEngine.GameObject[]”列表转换为 System.Collections.Generic.List>UnityEngine.GameObject<
最佳答案
GameObject.FindGameObjectsWithTag返回游戏对象的数组。
安array在 C# 中是一种存储多个相同类型对象的数据结构。
A list是对象的通用集合。
虽然数组和列表在概念上非常相似,但两者在数据访问和使用方面存在差异。通常,数组仅在创建时填充一次,之后才被读取,而列表可以随时更改其元素(一些注意事项适用)。
这个 StackOverflow 问题总结了为什么您可能想要一个而不是另一个:Array versus List<T>: When to use which?
在您的特定情况下,您希望对 GameObject 集合应用一些 Linq 排序,因此您需要将从 FindGameObjectsWithTag
接收的数组转换为列表。
您可以通过多种方式做到这一点。最简单的方法是在列表上使用构造函数重载来一次分配整个数组:
GameObject[] gameObjectArray = GameObject.FindGameObjectsWithTag("Player");
List<GameObject> gameObjectList = new List<GameObject(gameObjectArray);
此处提供一些其他选项:Conversion of System.Array to List
关于c# - UnityEngine.GameObject 与 Generic.List<UnityEngine.GameObject>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49808061/