Unity3D调用函数时出现的NullReferenceException报错的解决方法

今天在做封装网络模块的测试时遇到了这样的错误
NullReferenceException
UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine)

网上查了一下,才恍然,其实是我对Unity的运行机制没有理解透,先看看别人的解释:

Well, i just guess that the script (and / or the gameobject it’s attached to) has been destroyed, or you created the Wait-instance with “new” which would result in the same behaviour since a MonoBehaviour can’t live on it’s own.

这段就解释的很清楚了:使用new创建实例或该脚本依附的gameObject被销毁了,都会报这种错误,因为MonoBehaviour脚本不能独自存在,必须依附于某个GameObject,也就是说用GetComponent<脚本>()去获取脚本。

你可能感兴趣的:(Unity3D)