Unity中已做空值检查仍抛出NullReferenceException的问题求助
Unity中已做空值检查仍抛出NullReferenceException的问题求助
嘿,我最近遇到一个百思不得其解的问题,明明已经做了空值检查,但在调用委托的Invoke方法时还是抛出了NullReferenceException,想请大家帮忙排查一下!
我的代码是这样的:
Dictionary<string, Action<GameObject>> handlerDict= new Dictionary<string, Action<GameObject>>(); // handlerDict was initialized in the beginning and poped up with values properly early on. void Update() { if (obj1!= null && handlerDict.ContainsKey(obj1.tag)) { print($"obj1.name = {obj1.name}, obj1.tag = {obj1.tag}"); print($"handlerDict[obj1.tag] = {handlerDict[obj1.tag]}, obj2= {obj2}"); handlerDict[obj1.tag].Invoke(obj2); // I got NullReferenceException here } }
因为代码在Update()里,控制台刷了好多日志,格式都是这样的:
obj1.name = GameObjectName_xxx(Clone), obj1.tag = GameObjectName_xxx
handlerDict[obj1.tag] = System.Action`1[UnityEngine.GameObject], obj2= GameObjectName_YYY(Clone) (UnityEngine.GameObject)
NullReferenceException: Object reference not set to an instance of an object ClassNameA+<>c.b__274_9 (UnityEngine.GameObject x) (at Assets/_Scripts/XXX/XXX.cs:4407)
我本来觉得,前面的if判断加上这两行打印,已经能确保obj1、字典里的委托以及obj2都不是null了,但还是出了问题,是不是我漏掉了什么情况?
希望有大佬能指点一下,万分感谢!
备注:内容来源于stack exchange,提问作者ArtS
相关产品推荐
相关产品推荐

