Using object sender in OnSelectedUnitChanged instead of singleton

Olá Hugo,

Question around the use of the singleton for UnitActionSystem when it comes to the OnSelectedUnitChanged event. Could we not just use the sender object, cast it to UnitActionSystem (since we know that’s what is being sent) and access the GetSelectedUnit() method like that?

When you presented us with the challenge, my initial reaction was to write:

private void UnitActionSystem_OnSelectedUnitChanged(object sender, EventArgs empty)
{
        var selectedUnit = ((UnitActionSystem)sender).GetSelectedUnit();
        _meshRenderer.enabled = selectedUnit == unit;
}

Seems to work. Is there a specific reason to go with the Singleton here when the event is already giving us the sender object?

Cheers!
Paulo

1 Like

Yup that is absolutely a valid way to go about it. I just tend to avoid casting when possible so I find the code cleaner if you just access the singleton like it’s done in so many other places.
That way your patterns don’t change depending on the event type, or where you use it.
If you want to access the UnitActionSystem you go through the singleton regardless of where that code is running, that helps keep the code more consistent.

But yes your code is absolutely a valid solution.

2 Likes

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

Privacy & Terms