question
Comme illustré dans la figure ci-dessous, lorsque l'élément de tableau de la classe personnalisée est affecté, une erreur "NullReferenceException : la référence d'objet n'est pas définie sur une instance d'un objet" est signalée.
在这里插入代码片
Solution
En effet, le tableau doit être instancié avant de pouvoir lui attribuer une valeur après son initialisation.
Le bon code est :
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();
}
}
}