首页 > 解决方案 > Json Serialization in Unity - NullReferenceException : Object reference not set to an instance of an object

问题描述

I created several custom classes to read a json file in Unity.

Fruits.cs

[System.Serializable]
public class Fruits 
{
    public Apple[] apples;
}

Apple.cs

[System.Serializable]
public class Apple 
{
    public string appleName;
}

MyClass.cs

public class MyClass : MonoBehaviour{

private Fruits fruits;

public void classSetup(){
    StartCoroutine(JsonReader());     
    String appleName = fruits.apples[0].appleName;   -------> this is the line trigger the exception. 
    Debug.Log(appleName); 
}

Ienumerator JsonReader(){
   .........unrelated codes hidden...............
   if (Url.Contains(":/") || Url.Contains("://") || Url.Contains(":///"))
        {
            UnityWebRequest www = UnityWebRequest.Get(Url);
            yield return www.SendWebRequest();
            JsonText = www.downloadHandler.text;
        }

        fruits = JsonUtility.FromJson<Fruits>(JsonText);

}
}

The JsonReader (IEnumerator I created) works fine as the Debug.Log print out the appleName I expect but the line "String appleName ....." trigger an exception (NullReferenceException : Object reference not set to an instance of an object.)

I read posts about how to fix null exception, but was not able to find help on how to do that for a custom serialization class. Simply doing fruits = new Fruits() does not work. I suspect that's because I didn't instantiate the fields. But what if I have a lot of fields in Fruits class? And what if I can't just do "fruits.apples = new Apple[5]" because the length depends on json input and may not be 5?

Any help will be appreciated.

标签: c#jsonunity3d

解决方案


我不完全确定那个。但我认为问题在于,Unity 过早地到达字符串 apple 因为您启动了一个协程,并且在您创建 json 对象时,Unity 正在继续并尝试获取一个值,但这还不存在。因此,您可以尝试自定义事件。

//Create a delegate and and event to fire at a certain point of time
public delegate void FruitsLoadedEvent FruitsLoadedEvent();
public static event FruitsLoadedEvent OnFruitsLoaded;

public void classSetup(){
    //Subscribe to the event
    OnFruitsLoaded += CreateApple;
    StartCoroutine(JsonReader());     
}

Ienumerator JsonReader(){
    .........unrelated codes hidden...............
    if (Url.Contains(":/") || Url.Contains("://") || Url.Contains(":///"))
    {
        UnityWebRequest www = UnityWebRequest.Get(Url);
        yield return www.SendWebRequest();
        JsonText = www.downloadHandler.text;
    }

    fruits = JsonUtility.FromJson<Fruits>(JsonText);
    //Invoke the event after checking, if anyone is subscribed
    OnFruitsLoaded?.Invoke();
}

private void CreateApple() {
    String appleName = fruits.apples[0].appleName;
}

我真的希望对你有帮助!


推荐阅读