Mittwoch, 4. November 2020

Unity UI Element Button selection and click simulation via script

simulate select and click

using UnityEngine.EventSystems;
using UnityEngine.UI;

...

[SerializeField] private Button myButton;

...

// simulate click : 

ExecuteEvents.Execute(myButton.gameObject, new BaseEventData(EventSystem.current), ExecuteEvents.submitHandler);

// simulate selection : 

EventSystem.current.SetSelectedGameObject(myButton.gameObject);



------------------------------------------------------------------------

List<Button> shuffling

   private GameObject[] _buttonGameObjects;
   private int _buttonIndex = -1;

..

_buttonGameObjects = GameObject.FindGameObjectsWithTag("MenuButton");

..

// select next button

            if (_buttonIndex + 1 == _buttonGameObjects.Length)
                _buttonIndex = 0;
            else
               _buttonIndex++;
  EventSystem.current.SetSelectedGameObject(_buttonGameObjects[_buttonIndex]);

..

// select previous button


            if (_buttonIndex - 1 < 0)
                _buttonIndex = _buttonGameObjects.Length - 1;
            else
                _buttonIndex--;
          EventSystem.current.SetSelectedGameObject(_buttonGameObjects[_buttonIndex]);


-----------------------------------------------------

Get all Buttons nested in a GameObject below the Canvas. The demo structure is ...Canvas, MenuPageLanguageSelection, MenuButton1...

    private Canvas myCanvas;
    private GameObject myMenuPageLanguage;
    GameObject[] myMenuButtonGameObjects;

    private void Awake()
    {
         myCanvas = GameObject.FindObjectOfType<Canvas>(); // only one in scene
        myMenuPageLanguage = myCanvas.transform.GetChild(0).gameObject; 
        myMenuButtonGameObjects = new                       GameObject[myMenuPageLanguage.transform.childCount];
        for (int i = 0; i < myMenuPageLanguage.transform.childCount; i++)
        {
            myMenuButtonGameObjects[i] =                      myMenuPageLanguage.transform.GetChild(i).gameObject;
        }
}