Example: Multi Page UI

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using CupkekGames.UITK;

// Extend from UIViewComponent which sets up UIDocument.rootVisualElement as UIView
public class MultiPageUI : UIViewComponent
{
    // List to hold UIView instances for different pages
    private List<UIView> pages = new List<UIView>();

    protected override void Awake()
    {
        // Don't forget to call the base function for initial setup
        base.Awake();

        // Retrieve all page elements from the UI Document
        VisualElement pageElements = Parent.Query<VisualElement>("Page").ToList();
        
        // Check if there are any page elements
        if (pageElements.Count == 0)
        {
            Debug.LogError("No page elements found in the UI Document.");
            return;
        }

        // Create UIView for the first page
        UIView firstPage = new UIView(gameObject, pageElements[0]);
        // Add action that fades out and destroys this gameObject when ESC is clicked
        firstPage.AddAction(new UIViewActionEscape(FadeOutThenDestroy));
        // Add the first page to the list
        pages.Add(firstPage);
        
        // Create UIViews for the remaining pages
        for (int i = 1; i < pageElements.Count; i++)
        {
            // Create UIView with Invisible start visibility
            UIView page = new UIView(gameObject, pageElements[i], UIStartVisibility.Invisible);
            // Add action that returns to the previous page when ESC is clicked
            int previousPage = i - 1; // Cache to avoid bug: closure over loop variable
            page.AddAction(new UIViewActionEscape(() => SetPage(previousPage)));
            // Add the page to the list
            pages.Add(page);
        }
    }

    private void SetPage(int index)
    {
        // Validate the index to ensure it's within bounds
        if (index < 0 || index >= pages.Count)
        {
            Debug.LogError("Page index out of bounds.");
            return;
        }

        for (int i = 0; i < pages.Count; i++)
        {
            if (i == index)
            {
                pages[i].Fade.FadeIn();
            }
            else
            {
                pages[i].Fade.FadeOut();
            }
        }
    }
}

Last updated