Saturday, February 6, 2016

Delegates or Callbacks

Here is an example for using Delegates to achieve a callback capability.

In the class that is going to call the callback function:

public class PointBasketManager : MonoBehaviour
{
   public delegate void GameOverEvent ();

   private GameOverEvent game_over;

   public void SetGameOverCallback (GameOverEvent newCallback)
   {
      game_over = newCallback;
   }

   public void BasketTriggered (uint points)
   {
      // trigger game is over
      game_over ();
   }
}

The using class calls the function SetGameOverCallback() and passes in the function that should be called when game_over() is called.

public class GameSystem : MonoBehaviour

{
   void Start()
   {
      point_mgr.SetGameOverCallback(OnGameEnd);
   }

   public void OnGameEnd ()
   {
      // end game stuff

   }
}

No comments:

Post a Comment