Let me explain in simple terms.
For my new engine for old game in Unity, time has come to get the in-game menu back on its feet.
I encountered the following issue:
void Update()
{
// problem 1, upstream logic always returns same value according state (obvious you'll tell me)
bool isPaused = ...;
// problem 2, it gets forcibly shown when paused (obvious once again)
SetRaceMenuVisibility(isPaused);
// basically, I had to comment out previous line to wire-up my menu
}
I guess you get the point, immediate mode: things are always done in the loop.
Which means that my menu would always get shown, problem is there is focusing and selection, and therefore initialization/show cannot be done repeatedly.
So I came up with that N handlers pattern:
private static Action RacePauseHandler = RacePauseHandler1;
private static void RacePauseHandler1()
{
// if user paused the game, switch to handler that will open menu
if (Choice != -1) {
RacePauseHandler = RacePauseHandler2;
}
}
private static void RacePauseHandler2() // this gets called only once, exactly what we want
{
// open in-game menu (quick and dirty but that's not the point)
Object.FindAnyObjectByType<MenuManager>().ActivateDefault();
// switch to handler that either NOP or rinse/repeat whole process
RacePauseHandler = RacePauseHandler3;
}
private static void RacePauseHandler3()
{
// if user unpaused the game, switch back to handler that acts upon enabled pause
if (Choice == -1) {
RacePauseHandler = RacePauseHandler1;
}
}
void Update()
{
bool isPaused = ...; // like above, no change in upstream logic
RacePauseHandler(); // this will juggle with 3 methods
}
Basically, I end up with the 2nd method only called once (what I want), the menu works, it isn't constantly initialized as it was previously without that pattern to dodge the consequences of immediate mode.
Only problem is, it's quite bulky (I might have to do it for N other things).
Do you know of a more effective approach to tackle these kind of issues?
(knowing that I can't change (yet) most of upstream logic (little by little only), thus why I need this self-defensive code)
Hope that makes sense, thanks! 😁