Search Unity

What is the concept behind a "CanvasHook" delegate?

Discussion in 'Scripting' started by Xarbrough, Jan 7, 2016.

  1. Xarbrough


    Dec 11, 2014
    I was looking through the Unity Networking samples from this thread and wondered if there is any specific design pattern behind the use of the "CanvasHook" delegates.

    On the UI panel I find this:

    Code (CSharp):
    1. public class OfflineControlHooks : MonoBehaviour
    2. {
    3.     public delegate void CanvasHook();
    5.     public CanvasHook OnStartHostHook;
    7.     public void UIStartHost()
    8.     {
    9.         if (OnStartHostHook != null)
    10.             OnStartHostHook.Invoke();
    11.     }
    12. }
    Then there are gui controllers like this one:

    Code (CSharp):
    1. [Serializable]
    2. public class OfflineCanvasControl : CanvasControl
    3. {
    4.     public override void Show()
    5.     {
    6.         base.Show();
    8.         var hooks = canvas.GetComponent<OfflineControlHooks>();
    9.         if (hooks == null)
    10.             return;
    12.         hooks.OnStartHostHook = OnGUIStartHost;
    13.     }
    16.     public void OnGUIStartHost()
    17.     {
    18.         GuiLobbyManager.s_Singleton.StartHost();
    19.         GuiLobbyManager.s_Singleton.onlineCanvas.Show("Host");
    20.     }
    And finally in the NetworkLobbyManager:

    Code (CSharp):
    1. public class GuiLobbyManager : NetworkLobbyManager
    2. {
    3.     public OfflineCanvasControl offlineCanvas;
    5.     void OnLevelWasLoaded()
    6.     {
    7.         if (offlineCanvas != null) offlineCanvas.OnLevelWasLoaded();
    8.     }
    I do understand how the code works, the UI button calls the first hook, then the controller has another method subscribed to it and finally, the LobbyManager can forward method calls or also call a hook method.

    However, what's the benefit of this setup, instead of calling methods directly? Also, I wonder if this wouldn't be an example of when to use an interface, but maybe the CanvasHook delegate is used, because interface wouldn't be serializable as inspector fields.

    Looking forward to any insights, thanks a lot! :)
  2. Cosmas


    Jan 9, 2010
    I'm a bit confused about this myself. The immediate benefit I can see is that you can hammer out your UI first and then get to defining the interior methods later without having to relink things in the inspector if you REALLY have to restructure things. On the flip side however its a lot of jumping around within classes and if you're trying to debug it can be a hassle.