カスタムクラスの配列を初期化して割り当てるときのNullReferenceExceptionの問題に関するUnityスタディノート

質問

次の図に示すように、カスタムクラスの配列要素が割り当てられると、「NullReferenceException:オブジェクト参照がオブジェクトのインスタンスに設定されていません」というエラーが報告されます。
ここに画像の説明を挿入ここに画像の説明を挿入

在这里插入代码片

解決

これは、初期化後に値を割り当てる前に、配列をインスタンス化する必要があるためです。
正しいコードは次のとおりです。

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