- Home /
null reference immediately after reference works?
Problem solved
I simply made a careless error elsewhere.
Okay, this is driving me nuts. Here's my code:
ExampleScript someScript;
someScript = GetComponent<ExampleScript>();
someScript.DoSomething();
This is from a script called Foo. The object with Foo also has a component typeof ExampleScript. This code is in Start() on Foo.
When I launch, someScript.DoSomething(); works! (prints to Debug.Log)
But immediately I crash on the line above that with a null reference exception. To be clear, first it gets a reference, calls DoSomething() and then crashes with a null ref on the line above.
Bug?
edit; same scenario when declaring typed variable at class scope, assigning in inspector, and trying to use it. First it works, then it crashes. Nothing about the function I'm performing can destroy the component or nullify the reference.
Your problem resides in another piece of code. Also are you sure that DoSomething() is called by this piece of code?
Try using the debugger step by step to identify the problem.
I feel soooo foolish! It was, indeed, a careless error.