본문 바로가기
Unity/수업내용

[Unity UI] 1일차 Menu

by 왹져박사 2023. 2. 6.
728x90

UI 배우기 전에도 전체적인 구조 잡는 부분이 중요하겠다고 생각했지만, UI는 특히나 구조가 매우 중요하다고 느꼈다. 

UITabMenu에서 UIMenu들을 관리하고, UIMenu는 각각의 메뉴에 들어가는 txt, image를 관리한다. 

 

각각의 Menu button 클릭 - 클릭된 메뉴의 text색이 변하고 이미지 활성화

 

UITabMenu

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

public class UItabMenu : MonoBehaviour
{
    public UIMenu[] arrUIMenu;

    private UIMenu selectedUIMenu;

    void Start()
    {
        foreach (UIMenu uiMenu in this.arrUIMenu)
        {
            uiMenu.btn.onClick.AddListener(() =>
            {
                if (this.selectedUIMenu != null)
                {
                    this.selectedUIMenu.FocusOff();
                }
                uiMenu.FocusOn();
                selectedUIMenu = uiMenu;
            });

            uiMenu.onClick = (menuType) =>
            {
                Debug.Log(menuType);
            };
        }
    }
}

UIMenu

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

public class UIMenu : MonoBehaviour
{
    public enum eMenuType {
        Shop, Item
    }

    public Button btn;
    public TMP_Text txtName;        //메뉴명
    public GameObject focusGo;      //포커스 이미지

    public eMenuType menuType;
    public System.Action<eMenuType> onClick;

    private void Start()
    {
        this.btn.onClick.AddListener(() =>
        {
            this.onClick(this.menuType);
            FocusOn();
        });
    }

    public void FocusOn()
    {
        //글자 색 변경
        //F7DE9C

        string htmlString = "#F7DE9C";
        Color color;
        if(ColorUtility.TryParseHtmlString(htmlString, out color))
        {
            this.txtName.color = color;
        }


        //포커스 이미지 활성화
        this.focusGo.SetActive(true);
    }
    public void FocusOff()
    {
        //글자 색 변경
        //FFFFFF
        string htmlString = "#FFFFFF";
        Color color;
        if (ColorUtility.TryParseHtmlString(htmlString, out color))
        {
            this.txtName.color = color;
        }

        //포커스 이미지 비활성화
        this.focusGo.SetActive(false);
    }
}
728x90

'Unity > 수업내용' 카테고리의 다른 글

[Unity 3D] IK 역운동학  (0) 2023.05.22
[Unity UI] 2일차 Slider  (0) 2023.02.20
[Unity UI] 1일차 Button  (0) 2023.02.06
[Unity2D] Shooting Game 구조 만들기 연습  (0) 2023.02.03
[Unity 3D / 유니티 교과서] 7장 예제 Bamsongi  (0) 2023.02.01