unity使用StartCoroutine是提示NullReferenceException的解决方法

 今天使用StartCoroutine时报错,vs里面正常,unity能正常编译及运行,但是执行到调用这句话的地方就提示NullReferenceException 
  


感觉很奇怪,又查了下API,用法没有错误,一切正常,百度了一下,也没有好的解决方案


将参数改成字符串在进行测试,错误依旧


进入unity官方论坛搜索,在查阅了几十篇帖子后,一个帖子提到的事让我眼前一亮,赶紧测试,顺利运行


帖子地址


在最下面Bunny83的回答中


Just as a side note: Unity's coroutines always run on a script instance on which you called StartCoroutine. If this object gets destroyed all coroutines on thie instance are stopped immediately. When you change the scene, all objects from the old scene are destroyed except those who has been marked with DontDestroyOnLoad.

No matter where this script runs, if one of the three objects (avatar, startSpot, endSpot) is destroyed you'll get a null-ref-exception.

Also keep in mind that if you reload a scene all objects in the scene are created. Don't use DontDestroyOnLoad on objects in a scene that you want to load multiple times. Everytime you load the scene the object is created once more but the previous instances are still there if they contain a DontDestroyOnLoad.



没错,就是DontDestroyOnLoad 导致的,我的脚本挂在一个物体上,此物体上挂的脚本都是所有场景都需要的,


理所当然的,我把我这个所有场景都需要的脚本挂了上去,进而导致了这个问题


解决方法很简单,不要用DontDestroyOnLoad ,在需要的场景上另外挂上这个脚本



本章原创,转载请注明,谢谢


你可能感兴趣的:(unity3D学习)