- Home /
NullReferenceException in StartCoroutine
I am getting crash reports from players (using an automated error reporting system), although i cannot seem to reproduce this issue.
For some reason, a certain piece of code that starts a coroutine throws a null reference exception:
StartCoroutine(LoadLevelDelayed());
// This method is defined properly, returning an IEnumerator and yielding at certain points.
private IEnumerator LoadLevelDelayed()
{
// ...
}
This script is attached to a game object that is saved inside a scene (i've seen other posts where people tried to manually instantiate MonoBehaviour objects and that was the cause of failure).
Other information that may be related is that the call to StartCoroutine occurs inside an anonymous delegate, e.g:
public class Something : MonoBehaviour
{
public void SomeMethod()
{
CallAnotherMethod(
delegate(bool success)
{
StartCoroutine(LoadLevelDelayed());
});
}
private IEnumerator LoadLevelDelayed()
{
// ..
}
}
What else can lead to a NRE thrown when calling this method (StartCoroutine) ?
Answer by hangemhigh · Sep 08, 2014 at 08:37 AM
First, remove private from IEnumerator LoadLevelDelayed(); Try that... Where are you calling startCoroutine() from?
EDIT: That is the issue. I've been using coroutine and they worked very well. You can just call the startCouroutine function when your download is done. Coroutine runs at the same time with other codes
so just start coroutine after the download is done. Don't expect Unity to support every feature of C#. Just try what I just said. You will see what I am talking about. You don't need that get coroutine working.
It is a private method, there's no need to expose it outside of this class. I am calling it from the same class (like my example) so the private makes no difference.
Removing private doesn't not expose it to outside world. The default is not public. The default is private. Forget about the private thing I said. I think that the delegate stuff might be the problem here.
This way you call the function
public class Something : $$anonymous$$onoBehaviour
{
void Update(){
Some$$anonymous$$ethod();
}
public void Some$$anonymous$$ethod()
{
StartCoroutine(LoadLevelDelayed());
}
private IEnumerator LoadLevelDelayed()
{
// ..
}
}
When do you want to load level? What is
CallAnother$$anonymous$$ethod(
delegate(bool success)
{
StartCoroutine(LoadLevelDelayed());
});
suppose to do and when is it suppose to be called? I don't know what calls the CallAnother$$anonymous$$ethod function but the code I modified should work.
We are wrapping this code as a continuation (System.Action) and pass that down to some other code that eventually will call it (after downloading some stuff, it will invoke it). Why might that be an issue? i would look into that.