pjanec
Topic Author
Posts: 4
Joined: 12 Feb 2015, 21:46

[Unity] Adding NoesisGUIPanel dynamically

12 Feb 2015, 22:14

When trying to add a NoesisGUIPanel dynamically and initialize it with a XAML file I have to force call the private method NoesisGUIPanel.OnEnable via reflection to load the XAML into the panel.
var cameraGO = Camera.main.gameObject;
var gui = cameraGO.AddComponent<NoesisGUIPanel>();
gui._xamlFile = "Assets/Scripts/Gui/SystemMenu.xaml";
gui.GetType().GetMethod("OnEnable", BindingFlags.NonPublic | BindingFlags.Instance )
                     .Invoke(gui, new object[] {} );
var root = gui.GetRoot<UserControl>();
...
This works but it relies on the internal implementation of NoesisGUIPanel class and may change in future versions. Is there a better way of doing that?

Thanks, Petr
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: [Unity] Adding NoesisGUIPanel dynamically

14 Feb 2015, 20:54

NoesisGUIPanel was not designed to be used that way, but it can be easily refactorized to behave correctly in that scenario you exposed.

You can do it yourself now, and we can incorporate it in a future release. Just create a public function and call it from OnEnable():
public class NoesisGUIPanel : MonoBehaviour
{
  // ...

  public void LoadXaml(string xaml)
  {
    _xamlFile = xaml;
    LoadXaml();
  }

  private void LoadXaml()
  {
    // Create NoesisGUI System
    NoesisGUISystem.Create();

    // Create UI Renderer
    if (NoesisGUISystem.IsInitialized && _xamlFile.Length > 0 && _uiRenderer == null)
    {
      // ...
    }
  }

  void OnEnable()
  {
    LoadXaml();
  }
}
The code you posted will look like this:
var cameraGO = Camera.main.gameObject;
var gui = cameraGO.AddComponent<NoesisGUIPanel>();
gui.LoadXaml("Assets/Scripts/Gui/SystemMenu.xaml");
var root = gui.GetRoot<UserControl>();
...

Who is online

Users browsing this forum: Ahrefs [Bot], Semrush [Bot] and 72 guests