Options for notification/subscribing in Unity eg. using Events or other design patterns

Hi,

I have a few different manager classes and each basically handles different object creation.
I would like to have the managers notify each other when certain objects are created/destroyed.

There are probably many ways to do this - first off, I was wondering if there is a “correct” way to handle this problem or a best practice that Unity suggests… For example, a lot of games would have enemies and at least one main character. Is there a “right” way to keep track of enemies, scores, etc.

Unity has an event system - and I was thinking of implementing one of the behavioural design patterns eg. Mediator - although this might be overkill.

Advice would be great.

Thanks

You could try using a Callback

A good resource for understanding callbacks.

Managers should be as agnostic as possible. The second managers start referencing other managers, you have yourself a big ol’ pile of spaghetti in your code. I personally use collections of each major type of actor in my game and let those do the talking.

Something like this:

[CreateAssetMenu]
public class MonsterCollection : ScriptableObject
{
   private List<Monster> _monsters;

   public event Action<Monster> onMonsterAdded;
   public event Action<Monster> onMonsterRemoved;

   private void OnEnable()
   {
       _monsters = new List<Monster>();
   }

   public void Add(Monster monster)
   {
       if (_monsters.Contains(monster) == false)
       {
           _monsters.Add(monster);

           if (onMonsterAdded != null)
               onMonsterAdded(monster);
       }
   }

   public void Remove(Monster monster)
   {
       int index = _monsters.IndexOf(monster);

       if (index != -1)
       {
           _monsters.RemoveAt(index);

           if (onMonsterRemoved != null)
               onMonsterRemoved(monster);
       }
   }
}

Then create the MonsterCollection ScriptableObject in your project and start linking that to everything that needs to know about monsters. Make sure all your monsters register / deregister themselves in OnEnable and OnDisable. The beauty of a system like this is all the systems that can react to or read the data, like a HUD or Radar, without having to go through half a dozen “managers”.

1 Like

@GroZZleR thanks, that idea is cool.