UnityEngine.GameObject与Generic.List <unityengine.gameobject>

时间:2018-04-13 01:35:35

标签: c# unity3d

public void FindClosestEnemy()
{
    List<GameObject> pList = GameObject.FindGameObjectsWithTag("Player");                             
    pList.OrderBy(obj=>Vector3.Distance(FindLocalPlayer().transform.position, 
obj.transform.position)).ToList();
}

我不明白两个名单之间的区别。如何转换&#39; UnityEngine.GameObject []&#39;列表到System.Collections.Generic.List&gt; UnityEngine.GameObject&lt;

2 个答案:

答案 0 :(得分:3)

GameObject.FindGameObjectsWithTag会返回一个数组的GameObjects。

C#中的array是一种存储多个相同类型对象的数据结构。

list是对象的通用集合。

虽然阵列和列表在概念上非常相似,但在数据访问和使用方面两者之间存在差异。通常,数组仅在创建时填充一次,之后才读取,而List可以随时更改它的元素(有些警告适用)。

这个StackOverflow问题总结了为什么你可能想要一个在另一个上面:Array versus List<T>: When to use which?

在您的特定情况下,您希望将一些Linq排序应用于GameObject集合,因此您需要将从FindGameObjectsWithTag收到的数组转换为列表。

您可以通过多种方式完成此操作。最简单的方法是使用列表上的构造函数重载来一次分配整个数组:

GameObject[] gameObjectArray = GameObject.FindGameObjectsWithTag("Player");
List<GameObject> gameObjectList = new List<GameObject(gameObjectArray);

此处提供了其他一些选项:Conversion of System.Array to List

答案 1 :(得分:1)

正如 Steve 正确解释但我想以不同的方式回答:

实际上在您的代码中,您将数组类型对象(GameObject.FindGameObjectsWithTag("Player"))分配到列表类型(List<GameObject> pList)对象中,而该对象并非隐式支持由编译器。您必须将列表转换为数组类型:

List<GameObject> pList = new List<GameObject>(GameObject.FindGameObjectsWithTag("Player"));

在此之后,您将能够使用您的代码。

现在问题的第一部分

  

我不明白两个名单之间的区别。

实际上你问的是不同的b / w数组和列表以及你应该记住的主要区别是 当你有固定长度的数据时,你应该使用数组,如果你有可变长度的数据,然后使用List。

您还可以在stackoverflow上找到有关此主题的详细信息

  1. Array versus List: When to use which?
  2. How and when to abandon the use of arrays in C#?
  3. Why do we use arrays instead of other data structures?
  4. List explaniation by MSDN
  5. Arrays considered somewhat harmful
  6. Should I user array or list