Unity单元测试实例化空对象报错:NullReferenceException解决
以下是针对你遇到的空引用问题的排查和修复步骤:
确认预制体引用与路径正确性
空引用最常见的原因是localPlayer或pcPlayer预制体没在GameManager的Inspector面板赋值,或者预制体未放置在Resources目录下(若通过Resources加载)。你可以在InitControllers方法开头添加校验,快速定位问题:void InitControllers(GameMode mode) { if (localPlayer == null) { Debug.LogError("localPlayer预制体未赋值!"); return; } if (pcPlayer == null) { Debug.LogError("pcPlayer预制体未赋值!"); return; } // 后续实例化逻辑 }同时注意:Resources目录下的预制体名称要与加载时的字符串完全匹配(大小写敏感),若放在子目录中,路径需写成
"SubFolder/PlayerPrefab"格式。等待GameManager完成初始化再调用StartGame
在UnityTest的IEnumerator方法中,实例化预制体后,GameManager的Awake/Start方法不会立即执行,需等待至少一帧完成初始化。如果InitControllers在Awake或Start中触发,直接调用StartGame会导致逻辑执行顺序错误,引发空引用。修改测试代码如下:[UnityTest] public IEnumerator TestGameManagerStartGame() { // 加载并实例化GameManager预制体 var gmPrefab = Resources.Load<GameObject>("GameManager"); if (gmPrefab == null) { Debug.LogError("Resources中找不到GameManager预制体!"); yield break; } var gmObj = Object.Instantiate(gmPrefab); // 等待一帧,让Awake/Start执行完毕 yield return null; var gameManager = gmObj.GetComponent<GameManager>(); gameManager.StartGame(GameMode.Player); // 此处可添加断言逻辑 yield return null; }排查GameMode分支逻辑的正确性
检查InitControllers方法中,传入GameMode.Player时是否正确引用了localPlayer或pcPlayer,有没有变量名笔误,或是分支判断条件错误导致用到未赋值的对象。确保测试环境可访问预制体
若在Unity PlayMode测试中,需确认测试程序集能访问到Resources目录下的预制体。如果预制体放在Editor目录中,Runtime环境(包括PlayMode测试)无法访问,需将其移到非Editor的Resources目录内。
内容的提问来源于stack exchange,提问作者Noam Riahi

