1
\$\begingroup\$

Maybe it's a repeated subject in the community but other answers didn't solved my question...

I tried as the tutorial: http://answers.unity3d.com/questions/11021/how-can-i-send-and-receive-data-to-and-from-a-url.html and worked fine in start method but when I try:

public Class A
 {
 //    ...CODE...
 new B().JSONRequest(jsonString);
 }

public Class B
{

public void JSONRequest(string json) { 
string url = URL.LOCAL.url;
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json"); 
UTF8Encoding encoding = new System.Text.UTF8Encoding(); 
WWW request = new WWW(url, encoding.GetBytes(requisicaoJSON.ToCharArray()), HashtableToDictionary<string, string>(postHeader));
 print("Request: "+request); 

StartCoroutine(WaitForRequest(request));
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;
        // check for errors
        if (www.error == null)
        {
            Debug.Log("WWW Ok!: " + www.data);
        } else {
            Debug.Log("WWW Error: "+ www.error);
        }    
    }  
}

It gives me in the StartRoutine line: NullReferenceException UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineMonoBehaviourBindings.gen.cs:61

Console prints Request: UnityEngine.WWW so it does not appear to be null. –

\$\endgroup\$
  • 1
    \$\begingroup\$ Wait a sec, B is a MonoBehaviour, right? You should attach your B instance to a GameObject using gameObject.AddComponent<B>() - Unity warns you not to try to construct MonoBehaviours by saying new B() - I would not expect Coroutines to work on a floating MonoBehaviour that's not attached to a GameObject. \$\endgroup\$ – DMGregory Nov 25 '16 at 3:02
6
\$\begingroup\$

A bit of background on this:

StartCoroutine is a method provided by the MonoBehaviour base class.

MonoBehaviours are designed to be attached as components to GameObjects - Unity will warn you if you try to construct one with new, instead you should create them via gameObject.AddComponent<MyMonoBehaviourType>()

The GameObject is how the engine keeps track of MonoBehaviours from one frame to the next, so it's critical to methods designed to execute over multiple frames, ie. Coroutines. During StartCoroutine(), Unity will try to register the relationship between the coroutine and its parent GameObject (so that if the GameObject is destroyed/disabled, its coroutines can be stopped and not leaked). If it doesn't find a GameObject it will throw a null reference exception.

So, the fix is to ensure every MonoBehaviour is created as part of a GameObject - never construct them free-floating.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.