본문 바로가기
KDT/유니티 심화

23/09/04 LearnUGUI 버튼

by 잰쟁 2023. 9. 4.
728x90

배열 없이 버튼 클릭하여 출력해보기

 

UIMain

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

public class Test01UIMain : MonoBehaviour
{    
    public enum eButtonType 
    {
        Blue, Red, Green, Purple
    }


    [SerializeField]
    private Button btnBlue;
    [SerializeField]
    private Button btnRed;
    [SerializeField]
    private Button btnGreen;
    [SerializeField]
    private Button btnPurple;

    public System.Action<eButtonType> onButtonClicked;

    public void Init()
    {
        this.btnBlue.onClick.AddListener(() => {
            Debug.Log("blue 버튼 클릭 됨!");
            this.onButtonClicked(eButtonType.Blue);
        });

        this.btnRed.onClick.AddListener(() =>
        {
            Debug.Log("red 버튼 클릭 됨!");
            this.onButtonClicked(eButtonType.Red);
        });

        this.btnGreen.onClick.AddListener(() =>
        {
            Debug.Log("green 버튼 클릭 됨!");
            this.onButtonClicked(eButtonType.Green);
        });

        this.btnPurple.onClick.AddListener(() =>
        {
            Debug.Log("purple 버튼 클릭 됨!");
            this.onButtonClicked(eButtonType.Purple);
        });
    }
}

 

SceneMain

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

public class Test01Main : MonoBehaviour
{
    [SerializeField]
    private Test01UIMain uiMain;


    void Start()
    {
        //uiMain에 입력된 버튼 타입을 가져와서 출력
        this.uiMain.onButtonClicked = (btnType) =>
        {
            Debug.Log(btnType);
        };
        this.uiMain.Init();
    }

}