Unity/UI

체크박스 만들기

s0002 2023. 2. 7. 17:03

 

수업 시간에 완성한 것
집에서 다시 만들어 본 것

집에서 다시 만들어 보는데 체크박스가 두 개라서

한 곳을 누르면 다른 곳 상태가 변하게 만들어야 하나 싶었는데

보통 체크박스는 서로 다른 항목에 대해 체크하는 거니까 독립적으로 작동하게 만들었다

코드는 SwitchButton 만든 것을 참고해서 만들었다

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

public class UICheckBox : MonoBehaviour
{
    private bool state; //false , true 
    private Button btn;
    public GameObject[] offOn;  //0 : off, 1 : on 

    void Start()
    {
        this.btn = this.GetComponent<Button>();
        this.btn.onClick.AddListener(() => {
            Debug.Log("click!");
            this.ChangeCheckState();
        });

        this.Init();
    }

    private void Init()
    {
        this.state = false;
        this.Off();
    }

    private void On()
    {
        offOn[0].SetActive(false);
        offOn[1].SetActive(true);
    }

    private void Off()
    {
        offOn[0].SetActive(true);
        offOn[1].SetActive(false);
    }

    public void ChangeCheckState()
    {
        var current = !this.state;
        Debug.LogFormat("prev: {0}, current: {1}", this.state, current);
        if (current) this.On();
        else this.Off();
        this.state = current;   //변경된 상태로 갱신 
    }
}