question
As shown in the figure below, when the array element of the custom class is assigned, an error "NullReferenceException: Object reference not set to an instance of an object" is reported.
在这里插入代码片
solution
This is because the array must be instantiated before it can be assigned a value after it is initialized.
The correct code is:
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;
// Start is called before the first frame update
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();
}
}
}