Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Event System with callbacks

Discussion in 'Scripting' started by Darkhalo45, Apr 9, 2018.

  1. Darkhalo45

    Darkhalo45

    Joined:
    May 7, 2016
    Posts:
    18
    I am implementing an event system in my game, but I am not too sure how to also implement a callbacks into the system. Now I just have a delegate and two events for it, one is the a normal event and the other one is a callback. Here's an example:
    Code (CSharp):
    1. public delegate void LoadGame(int sceneID);
    2.     public event LoadGame LoadGameAction;
    3.     public event LoadGame LoadGameCallback;
    I don't feel like this is an efficient and good way to make callbacks.
     
  2. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    What do you mean "one is the a normal event and the other one is a callback"? What do you see is the difference here?

    I actually don't bother with making a delegate definition. In fact, I avoid it because whenever I see an event that uses "SomeDelegate" definition, I have to go and look it up to know what parameters I'm expected to pass in. So I just do stuff like this:

    Code (csharp):
    1.  
    2. public event Action<int> OnValueChanged;
    3. public event Action OnUpdated;
    4.  
    and so on...
     
    lordofduct likes this.
  3. Darkhalo45

    Darkhalo45

    Joined:
    May 7, 2016
    Posts:
    18
    What I mean is that, when I want to load a game, I want my loading method to send a callback when the game data has been loaded, so other scripts know that the game can continue or start.
     
  4. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    This is an event:
    public event LoadGame LoadGameAction;
    .

    This is a callback:
    public void LoadLevel(int level, Action<int> OnLevelLoaded) {...}


    With events, you can have multiple listeners. With callbacks, well, there's usually only one listener -- the caller. Sure, you could rework it so you can support multiple listeners for callbacks... but in that case you might as well use events instead.

    It's up to you to decide which approach makes the most sense. Personally I'd use events. They help keep the UI and game logic from getting tied together into a spaghetti mess of code.