首页 > 解决方案 > 将类型列表gameObjects添加到GameObject列表时获取null

问题描述

private List<GameObject> objectsToSave;

    private void Awake()
    {
        SaveSystem.Init();

        //objectsToSave = GameObject.FindGameObjectsWithTag("My Unique ID").ToList();
        var objectsWithGenerateGuid = GameObject.FindObjectsOfType<GenerateGuid>().ToList();
        if (objectsWithGenerateGuid.Count > 0)
        {
            for (int i = 0; i < objectsWithGenerateGuid.Count; i++)
            {
                objectsToSave.Add(objectsWithGenerateGuid[i].gameObject);
            }
        }
    }

我第一次使用 FindGameObjectsWithTag 但我遇到了一个问题,例如 MainCamera,因为我将要保存标签的对象更改为“我的唯一 ID”,然后整个场景都找不到 MainCamera。因此,我想按组件查找要按标签保存的对象。

这就是我将 Generate Guid 组件脚本添加到我要保存的对象的方式:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class GenerateAutomaticGuid : Editor
{
    [MenuItem("GameObject/Generate Guid", false, 11)]
    private static void GenerateGuid()
    {
        foreach (GameObject o in Selection.gameObjects)
        {
            var g = o.GetComponent<GenerateGuid>();
            if (!g) g = o.AddComponent<GenerateGuid>();
            g.GenerateGuidNum();
        }
    }
}

我可以看到 objectsWithGenerateGuid 包含例如 5 个项目,但是当我尝试将它们添加到 List objectsToSave 时,我在行上遇到了 null 异常:

objectsToSave.Add(objectsWithGenerateGuid[i].gameObject);

主要目标是找到包含脚本 GenerateGuid 的所有对象并将它们添加到列表 objectsToSave。

标签: c#unity3d

解决方案


先尝试初始化列表

private List<GameObject> objectsToSave = new List<GameObject>();

由于计数objectsWithGenerateGuid.Count大于 0,所以我认为objectsToSavenull这样,这就是为什么你得到空指针异常。


推荐阅读