问题
像下图一样,当自定义类的数组元素赋值时,报错“NullReferenceException: Object reference not set to an instance of an object”。
在这里插入代码片
解决方案
这是因为数组初始化后要先实例化才能赋值。 正确的代码是:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CustomClass
{
public string name;
public GameObject gameObject;
}
public class CustomClassArray : MonoBehaviour
{
public GameObject parent;
[SerializeField]public CustomClass[] myArray;
void Start()
{
myArray = new CustomClass[parent.transform.childCount];
for(int i = 0; i < parent.transform.childCount; i++)
{
myArray[i] = new CustomClass();
myArray[i].gameObject = parent.transform.GetChild(i).gameObject;
myArray[i].name = parent.transform.GetChild(i).gameObject.name.ToString();
}
}
}
|