Search Unity

What is the concept behind a "CanvasHook" delegate?

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

  1. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    I was looking through the Unity Networking samples from this thread http://forum.unity3d.com/threads/networking-sample-projects.325096/ 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();
    4.  
    5.     public CanvasHook OnStartHostHook;
    6.  
    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();
    7.  
    8.         var hooks = canvas.GetComponent<OfflineControlHooks>();
    9.         if (hooks == null)
    10.             return;
    11.  
    12.         hooks.OnStartHostHook = OnGUIStartHost;
    13.     }
    14.  
    15.  
    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;
    4.  
    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

    Cosmas

    Joined:
    Jan 9, 2010
    Posts:
    133
    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.