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

Find GameObject to which Panel is attached

Discussion in 'UI Toolkit' started by awmuncy, Nov 11, 2020.

  1. awmuncy

    awmuncy

    Joined:
    Jan 27, 2020
    Posts:
    4
    I have a GameObject with a UIDocument attached to it. How would I go about finding that GameObject from an element once the element is added to the UIDocument's panel?

    Code (CSharp):
    1. public class ControlPanel : VisualElement
    2. {
    3.     public new class UxmlFactory : UxmlFactory<ControlPanel> {}
    4.     public ControlPanel()
    5.     {
    6.         this.RegisterCallback<AttachToPanelEvent>(evt => {
    7.            var panel = evt.destinationPanel;
    8.            // How might I find the GameObject from here?
    9.         });
    10.         var inPlay = UIHelper.GetTemplate("UITemplates/Organisms/GrandCentralModel");
    11.         this.Add(inPlay);
    12.     }
     
  2. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,203
    Ideally, UI does not directly interact with GameObjects. It should be the other way around. GameObjects should register for UI events and make the appropriate changes. Otherwise, you risk mixing UI with game logic which will in the long run diminish the advantages that UI Toolkit offers (over uGUI).

    Can you add a bit more context to what you're trying to do so I can help suggest an alternative approach. You cannot get the GameObject from the UI panel (at least not without hacks and reflection magic). This is by design. My question is what do you wish to do with this reference if you did get it?
     
  3. awmuncy

    awmuncy

    Joined:
    Jan 27, 2020
    Posts:
    4
    I was going to create an event originating from the GameObject, and subscribe to it from the UI element. After reading your post, and some consideration, I've come to think it makes more sense that the GameObject would subscribe an event originating from UI, and if the GameObject needs to change the UI be, it should be more imperative about it.
     
  4. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,203
    Yes, that's the intendent flow with UI Toolkit.