- Home /
Why does this give a "nullReferenceException"?
class some : MonoBehaviour
{
public some()
{
Invoke("wait", 2.0f);
}
void wait()
{
}
}
Just making an instance of this class gives me a "nullReferenceException" for some reason.. same happens when trying to call a corouritine from this class.
And before someone suggests not inheriting from MonoBehaviour, i can't because i really want to have a delay and unity has made that impossible without a MonoBehaviour.
Answer by hexagonius · Nov 07, 2018 at 10:03 PM
you must not use a constructor for MonoBehaviour derived classes at all. those solely exist on gameobjects, either in the scene or on prefabs. For the latter use Instatiate to make one.
Answer by Matt1000 · Nov 07, 2018 at 10:51 PM
As they said, you shouldn't use constructors in component classes. If you need to call a method as soon as the object is created (either when you instantiate a new object or the scene is loaded with it) you should do it in Start or in Awake. Those to are automatically called. If you want a non-component class then just remove the inheritance from Monobehaviour.
Your answer
Follow this Question
Related Questions
Problem accessing public method of script attached to gameobject. 0 Answers
NullReference in script? Prefab is linked in inspector 2 Answers
RayCastHit.transform.gameObject.GetComponent works in editor but not in standalone build 0 Answers
After Instantiating a Prefab I get a NullReference Error even though the Object was created 2 Answers
HELP!!! This NullReferenceException won't go away! :( 1 Answer