Forum rules - please read before posting.

Turning on a UnityUI Menu triggers OnEnable\OnDisable methods multiple times

edited May 2021 in Technical Q&A

[Unity v2019.4.26f1 - AC v1.73.7]

Hi Chris!

While trying to create a more complex UI, using Unity UIs as a Menu source, I noticed that when the Menu first gets turned on, the OnEnable\OnDisable scripts attached to my Panels get triggered in (to me) unexpected ways.

I successfully reproduced the issue in AC's 2D Demo, by converting the Pause menu to a Unity UI one and using the PauseUI prefab provided in the AdventureCreator/UI/ folder and attaching the following simple script to its Panel GameObject.

private void OnEnable()
{
    Debug.Log("TestPauseUIPanel --- OnEnable");
}

void Start()
{
    Debug.Log("TestPauseUIPanel --- Start");
}

private void OnDisable()
{
    Debug.Log("TestPauseUIPanel --- OnDisable");
}

When I hit the Input Key to toggle the Menu, this is what happens in the Console:

This doesn't happen all the time, but surely it does when the Menu is turned on for the first time.

I found this out while trying to create a "navigable top bar" UI that:

  • when enabled, turns on a default menu
  • lets you switch between "tabs"
  • when disabled, would also turn off whatever "tab" was on at the moment.

Am I doing anything wrong? I hope I provided enough information!

As always, thanks a lot in advance.

Comments

  • There are times when AC needs to enable/disable a UI menu within a single frame - its initial spawning being one of them.

    If you're trying to run code when a particular menu is being turned on/off, hook into the OnMenuTurnOn/Off events:

    public Canvas canvas;
    
    private void OnEnable ()
    {
        EventManager.OnMenuTurnOn += OnMenuTurnOn;
        EventManager.OnMenuTurnOff += OnMenuTurnOff;
    }
    
    private void OnDisable ()
    {
        EventManager.OnMenuTurnOn -= OnMenuTurnOn;
        EventManager.OnMenuTurnOff -= OnMenuTurnOff;
    }
    
    private void OnMenuTurnOn (AC.Menu menu, bool isInstant)
    {
        if (menu.RuntimeCanvas == canvas)
        {
            // This menu was turned on
        }
    }
    
    private void OnMenuTurnOff (AC.Menu menu, bool isInstant)
    {
        if (menu.RuntimeCanvas == canvas)
        {
            // This menu was turned off
        }
    }
    
  • Thanks a lot, Chris! I'll convert my code to just use EventManager events.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Welcome to the official forum for Adventure Creator.