Otwieranie i zamykanie paneli UI w Unity

Przykład stworzenia prostego menu na podstawie paneli UI

Odwołania do paneli i przycisków dołączamy w inspektorze

using UnityEngine;
using UnityEngine.UI;

public class SidePanelContols : MonoBehaviour
{
    public Button btn1;
    public Button btn2;
    public Button btn3;
    public Button btn4;
    public GameObject[] panele;

    void Start()
    {
        btn1.GetComponent<Button>().onClick.AddListener(() => OpenPanel(0));
        btn2.GetComponent<Button>().onClick.AddListener(() => OpenPanel(1));
        btn3.GetComponent<Button>().onClick.AddListener(() => OpenPanel(2));
        btn4.GetComponent<Button>().onClick.AddListener(() => OpenPanel(3));
        CloseAllPanels();
    }


    void CloseAllPanels()
    {
        foreach (var panel in panele)
        {
            panel.SetActive(false);
        }
    }

    void OpenPanel(int panelIndex)
    {
        if(panele[panelIndex].activeInHierarchy)
        {
            panele[panelIndex].SetActive(false);
        }
        else
        {
            CloseAllPanels();
            panele[panelIndex].SetActive(true);
        }
    }
}
Scroll to Top