Unity JSON 创建显示数组错误
Unity JSON creation showing error on array
当我尝试使用以下代码创建 JSON 时,它在此处显示空异常错误。
myObject.test[0]="0";
myObject.test[1]="1";
myObject.test[2]="2";
如何解决这个问题
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JSON_Manager : MonoBehaviour
{
public string JSON;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Node myObject = new Node();
myObject.BrickName = "test";
myObject.LED=false;
myObject.test[0]="0"; //error
myObject.test[1]="1";
myObject.test[2]="2";
string JSON = JsonUtility.ToJson(myObject);
print(JSON);
}
}
[System.Serializable]
public class Node
{
public string BrickName;
public bool LED;
public string[] test;
}
发生此错误是因为您没有初始化数组。初始容量为0,所以报错
修复它的最简单方法是在访问字符串之前像这样编写,或者创建将为您完成此操作的默认构造函数:
test = new string[size you need]
当我尝试使用以下代码创建 JSON 时,它在此处显示空异常错误。
myObject.test[0]="0";
myObject.test[1]="1";
myObject.test[2]="2";
如何解决这个问题
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JSON_Manager : MonoBehaviour
{
public string JSON;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Node myObject = new Node();
myObject.BrickName = "test";
myObject.LED=false;
myObject.test[0]="0"; //error
myObject.test[1]="1";
myObject.test[2]="2";
string JSON = JsonUtility.ToJson(myObject);
print(JSON);
}
}
[System.Serializable]
public class Node
{
public string BrickName;
public bool LED;
public string[] test;
}
发生此错误是因为您没有初始化数组。初始容量为0,所以报错
修复它的最简单方法是在访问字符串之前像这样编写,或者创建将为您完成此操作的默认构造函数:
test = new string[size you need]