c# - 将类型列表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。
解决方案
先尝试初始化列表
private List<GameObject> objectsToSave = new List<GameObject>();
由于计数objectsWithGenerateGuid.Count
大于 0,所以我认为objectsToSave
是null
这样,这就是为什么你得到空指针异常。
推荐阅读
- linq - EFCore 2.2 GroupBy Sum 和 DateDiff
- angular - 如何在角度 highcharts 模块中修复“类型中缺少属性'类型'但类型'SeriesXrangeOptions'中需要”
- c# - ReactiveUI 的 IViewFor 的目的是什么
(及其实现类型)在 WPF 中? - javascript - 带有引导程序 vue 的可拖动表
- python - 无法使用 pip 安装 toripchanger
- sql - 将 Unix 时间转换为 DateTime 103
- python - Python:内容
- 在 BeautifulSoup 的列表中
- android - 如果任何其他应用程序尝试连接需要断开连接,我们如何实现 BLE 外围设备仅连接到我们的 Android 应用程序(中央)
- kubernetes - 如何在 Kubernetes 中实现多租户?
- python-2.7 - 如何检测图像是否可以粘贴背景?