c# - UnityEngine.GameObject 与 Generic.List<UnityEngine.GameObject>

标签 c# unity3d

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/

相关文章:

c# - NHibernate 中具有不同类型答案的问题

c# - Ubuntu上的Unity/C#和Python通信

Android Developer Console - 使用 Android Studio 发布构建后指纹错误

c# - Unity3d 的记录器,与 MonoDevelop 很好地连接

c# - BindingFlags - 获取所有这些(最大成员数)

c# - 在 Unity3D 中,从数字中删除除了一定数量的小数以外的所有内容

c# - 无法加载资源 (.resx) 文件,因为它不受信任

c# - 如何在 C# 中使用 'union' 2 个或更多数据表?

c++ - 读取dll文件中的文本文件

c# - 用鼠标移动对象但不移动到鼠标指针所在的位置