[Unity] Base Class 만들기

Yerin·2023년 7월 21일
0

앞선 포스트에서 만들었던 Bind와 Get 함수는 UI가 늘어남에 따라 그때마다 복붙하여 새로 만들어 줄 수 없으니 Base 클래스를 만들어보자!

UI_Base.cs

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

public class UI_Base : MonoBehaviour
{
    protected Dictionary<Type, UnityEngine.Object[]> _objects = new Dictionary<Type, UnityEngine.Object[]>();
    protected void Bind<T>(Type type) where T : UnityEngine.Object
    {
        string[] names = Enum.GetNames(type);
        UnityEngine.Object[] objects = new UnityEngine.Object[names.Length];
        _objects.Add(typeof(T), objects);

        for (int i = 0; i < names.Length; i++)
        {
            if (typeof(T) == typeof(GameObject))
                objects[i] = Util.FindChild(gameObject, names[i], true);
            //Debug.Log($"Failed to bind{names[i]}");
            else
                objects[i] = Util.FindChild<T>(gameObject, names[i], true);

            if (objects[i] == null)
                Debug.Log($"Failed to bind{names[i]}");

        }
    }

    protected T Get<T>(int idx) where T : UnityEngine.Object
    {
        UnityEngine.Object[] objects = null;
        if (_objects.TryGetValue(typeof(T), out objects) == false)
            return null;

        return objects[idx] as T;
    }

    protected Text GetText(int idx) { return Get<Text>(idx); }

    protected Button GetButton(int idx) { return Get<Button>(idx); }


    protected Image GetImage(int idx) { return Get<Image>(idx); }


}

UI_Button 스크립트는 UI_Base를 상속받아 간접적으로 MonoBehaviour을 상속받게 된다.

UI_Button.cs

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

public class UI_Button : UI_Base
{
 

    enum Buttons
    { 
        PointButton
    }


    enum Texts
    { 
        PointText,
        ScoreText
    }

    enum GameObject
    { 
        TestObjectzz,
    }
    private void Start()
    {
        Bind<Button>(typeof(Buttons));
        Bind<Text>(typeof(Texts));

        Get<Text>((int)Texts.ScoreText).text = "Bind Test";
    }
   
    int _score = 0;
    public void OnButtonClicked() {
        _score++;
        
    }
}

아래와 같은 오류가 뜬다면 UI_Base.cs의 함수를 protected 형식으로 바꿔보자!

profile
재밌는 코딩 공부

0개의 댓글