【发布时间】:2021-05-26 18:39:02
【问题描述】:
我有一个 C# 脚本可以归结为:
public class SingletonTest : MonoBehaviour
{
public static SingletonTest Singleton = null;
public int Value = 42;
void Start() {
Singleton = this;
}
}
起初运行良好,但我的问题是,当我编辑脚本然后单击返回 Unity 编辑器/IDE 时,我在其他类中得到一整串 NullReferenceExceptions 用于行 SingletonTest.Singleton.Value .
我用谷歌搜索了一下,这个编辑器重新加载似乎触发了一个名为 Domain Reloading (see also) 的进程。 显然域重新加载也会重置所有静态字段,这解释了我的错误消息。我尝试了该页面上建议的一些解决方法,但都不起作用:
using UnityEngine;
public class SingletonTest : MonoBehaviour
{
public static SingletonTest Singleton = null;
public int Value = 42;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void StaticStart()
{
var arr = FindObjectsOfType<SingletonTest>();
Debug.Log($"Len arr: {arr.Length}"); // This is 0! :(
if (arr.Length > 0)
Singleton = arr[0];
}
void Start()
{
Singleton = this;
}
void OnAfterDeserialize()
{
Singleton = this;
}
}
我可以通过将Singleton = this 放入Update() 函数来使其工作,但该解决方案很丑陋,并且在重新加载后的第一帧上仍然给我一个NullReferenceException。
(请不要建议将Value 字段设为静态,这只是一个简化示例,我确实需要/想要一个单例类)
【问题讨论】:
-
您在运行时或编辑器中需要这个?
-
我发现将这个问题作为一个副本关闭是不合适的。我明确设置了字段,但重新加载域的过程会重新构建对象,但不是专门构建它们的静态字段,这远非显而易见。
标签: c# unity3d static unity3d-editor