【问题标题】:C#: How can I convert an array of GameObjects into a list or array of Transforms [duplicate]C#:如何将游戏对象数组转换为变换列表或数组[重复]
【发布时间】:2018-04-02 14:25:26
【问题描述】:

这是我的代码:

GameObject[] targets;
List<Transform> transformlist;

void Start () {
    targets = GameObject.FindGameObjectsWithTag("target");
    Debug.Log(targets.Length);
    foreach (GameObject obj in targets)
    {
        Transform transform = obj.transform;
        transformlist.Add(transform);
    }
    Debug.Log(transformlist.Count);

}

我需要这样做,因为我希望我的相机指向最近的游戏对象,我稍后会在我的脚本中编写。不管我尝试什么(数组或列表)它仍然说

"NullReferenceException: 对象引用未设置为 对象”。

但是,我的第一个 "Debug.Log(targets.length)" 返回 5400,这是带有“目标”标签的游戏​​对象的实际数量,所以我知道它至少已经到了那么远。

这是复杂的事情还是我只是愚蠢? 非常感谢所有提供帮助的人。

【问题讨论】:

  • 你在初始化transformList吗?

标签: c# arrays list transform gameobject


【解决方案1】:

foreach 之前:

transformlist = new List<Transform>();

foreach 内部:

Transform transform = obj.transform;
transformlist.Add(transform);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    相关资源
    最近更新 更多