设备:Surface Pro 8
Unity编辑器版本:2021.3.11f1c2(LTS)
前言
最近写场景切换时为一个物体设置了DontDestroyOnLoad,在切换场景并切换回来时也考虑到了绑定内容消失的可能性,在Awake()里面写了负责赋值的部分,但是赋值的变量仅仅可用一次之后依旧为空导致NullReferenceException。
public class TEST: MonoBehaviour
{
public static TEST instance;
public GameObjectComponent GOC;
private void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(gameObject);
instance = this;
}
var goc = GameObject.Find("GameObject");
if (goc)
{
GOC = go.GetComponent<GameObjectComponent>();
}
}
//之后调用GOC的代码……
}
解决方法
方法1
订阅事件,在切换场景的时候调用代码。
public class TEST: MonoBehaviour
{
public static TEST instance;
public GameObjectComponent GOC;
private void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(gameObject);
instance = this;
SceneManager.sceneLoaded += SceneLoading;
}
var goc = GameObject.Find("GameObject");
if (goc)
{
GOC = go.GetComponent<GameObjectComponent>();
}
}
private void SceneLoading(Scene scene, LoadSceneMode mode)
{
var goc = GameObject.Find("GameObject");
if (goc)
{
GOC = go.GetComponent<GameObjectComponent>();
}
}
//之后调用GOC的代码……
}
方法2
在Update()中不断判断值是否空缺。
public class TEST: MonoBehaviour
{
public static TEST instance;
public GameObjectComponent GOC;
private void Awake()
{
if (instance == null)
{
DontDestroyOnLoad(gameObject);
instance = this;
}
var goc = GameObject.Find("GameObject");
if (goc)
{
GOC = go.GetComponent<GameObjectComponent>();
}
}
private void Update()
{
if (GOC == null && SceneManager.GetActiveScene().name == "SceneName")
{
var goc = GameObject.Find("GameObject");
if (goc)
{
GOC = go.GetComponent<GameObjectComponent>();
}
}
}
//之后调用GOC的代码……
}
问题原因
不明,望大佬解答。