Page 1 of 1

[Unity] Adding NoesisGUIPanel dynamically

Posted: 12 Feb 2015, 22:14
by pjanec
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

Re: [Unity] Adding NoesisGUIPanel dynamically

Posted: 14 Feb 2015, 20:54
by sfernandez
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>();
...