Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Other Runtime - SetActive(false) or enabled = false will lose event binding

Discussion in 'UI Toolkit' started by brainwipe, Jan 2, 2023.

  1. brainwipe

    brainwipe

    Joined:
    Aug 21, 2017
    Posts:
    74
    I discovered that if you make a game object containing a UIDocument inactive or you disable the UIDocument. Then any event bindings will be lost.

    If you need to hide the document, use root visibility instead.

    For example:

    Code (CSharp):
    1. public class MyClass : Monobehaviour
    2. {
    3.     [SerializeField]
    4.     private UIDocument document; // set in inspector
    5.  
    6.     private void Start()
    7.     {
    8.         var myButton = document.rootVisualElement.Q<Button>("nameOfMyButton");
    9.         myButton.clicked += () => Debug.Log("Button is clicked");
    10.  
    11.         document.enabled = false; // Don't do this! Event binding lost!
    12.         gameObject.SetActive(false); // Don't do this! Event binding lost!
    13.  
    14.         document.rootVisualElement.visible = false; // DO THIS!
    15.     }
    16. }
    In my case it was the "escape" menu that I was trying to create and then hide.

    I used the UI Toolkit Event Debugger to see that the events were being fired on the buttons but no methods were called.

    Posting here because it drove me mad for 3 hours.
     
    mashermack, Hellfim and unity_key4 like this.
  2. unity_key4

    unity_key4

    Joined:
    May 19, 2022
    Posts:
    6
    Oh man, thank you. I also got this problem. You are genius
     
    mashermack and brainwipe like this.