Unity学习笔记 关于自定义类的数组初始化赋值时 NullReferenceException 的问题

问题

像下图一样,当自定义类的数组元素赋值时,报错“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;
    
    // 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();
        }
    }   
}

猜你喜欢

转载自blog.csdn.net/weixin_42358083/article/details/122441858