c# - 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.
解决方案
我不完全确定那个。但我认为问题在于,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;
}
我真的希望对你有帮助!
推荐阅读
- swift - 选择器在 editMode 处于活动状态时不工作
- code-generation - 使用 MILO 客户端为 OPC-UA 信息模型生成类
- r - 在 R 中制作 plot_ly 图的子图
- java - 如何从仍在运行的进程中正确读取 std
- c# - 如何在 C# 中获取目录文件句柄?
- sapui5 - Where does the "exit" method come from? Where is it documented?
- pyomo - 用 pyomo 求解 MIQP - 设置为正值的变量在迭代期间变为零
- forms - 提交表单时无法登录cypress
- javascript - 如何在 html 中设置预选按钮的样式,以便选择的选项不显示在下拉列表中?
- linux - 在 Linux 中从 root 用户获取 Git 失败