Why use event when there is already Singleton?

Hi, really enjoying the course so far thanks heaps.
I am curious as to why GridSystemVisual is listening to an event to trigger UpdateSelectedGridVisual when we already made it a Singleton why not just access the function directly ?

We’re using the event so that we’re only updating the grid system visual when there is actually something to change. This is more efficient than checking and updating the visual every Update() loop by accessing the Singleton.

I do not mean to continue calling this on every update. In the video we create an event in LevelGrid that is invoked by the UnitMovedGridPosition function, then GridSystemVisual is subscribed to said event and calls UpdateSelectedGridVisual. Why not instead call GridSystemVisual.Instance.UpdateSelectedGridVisual(); from UnitMovedGridPosition.

With visuals, we tend to want to follow an Observer pattern, which what is set up here. The GridSystemVisual subscribes to an event, and the event is called by the caller without regards to who may be calling the event.
One thing we try to avoid in our code is cross dependency. GridSystemVisual already depends on LevelGrid, when possible, we should avoid also having LevelGrid depend on GridSystemVisual. This can lead to difficult to diagnose bugs in our code.

1 Like

OK great that does make sense, thanks for clarifying that :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms