困った時の自分用メモ

読んだ本を考察してメモったり、自分でいじった物の感想をメモったりする場。週1更新を目指します。

Unityの話~SerializedFieldの値を、自動で設定する~

表題の通り。 UnityのUI設定などで、SerializedFieldへの参照保持は良く使うと思うが、量が増えてくると、さすがにエディター上で全ての設定をするのは手間がかかってくる。
調べてみると、どうやらスクリプト上にプログラムを書くだけで、該当のオブジェクトの参照設定が可能なようなので、メモしておく。

こんな構成があるとして、 f:id:mochimoffu:20200819003645p:plain

Buttonに下記のResetAndNetSerializedFiled.csを貼り付ける

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ResetAndNetSerializedFieldTest : MonoBehaviour
{
    [SerializeField]
    private Image ThisImage = null;

    [SerializeField]
    private Image[] ChildThisImages = new Image[2];// Resetで設定する時は、きちんと必要分NEWをする

    // https://docs.unity3d.com/ja/current/ScriptReference/MonoBehaviour.Reset.html
    void Reset()
    {
        ThisImage = GetComponent<Image>();

        Image[] list = GetComponentsInChildren<Image>();

        for (int i = 0; i < list.Length; i++) {
            if (list[i].name == "Image1") {
                ChildThisImages[0] = list[i];
            } else if (list[i].name == "Image2") {
                ChildThisImages[1] = list[i];
            }
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

そうすると、コンポーネントをアタッチした時か、右クリメニューResetを押した時に、設定されるようになる。

リファレンスは、ここ

docs.unity3d.com

参考はここ

tsubakit1.hateblo.jp