How can I stop executing a method with an Action?
Hi! I'm making a test project just to check an idea I had ant to experiment a bit with Actions and callbacks (which I'm not really familiar with).
The game has an in-game timer that has nothing to do with actual time: in-game time passes only when the player does some interactions. So I set up a TImeManager class with this method that gets called whenever the player does something that costs time:
//Version 1
public void IncreaseTime()
{
while (addedTime > 0)
{
if (minutes < 60)
{
minutes++;
}
else if (hours < 23)
{
minutes = 0;
hours++;
}
else
{
hours = 0;
minutes = 0;
days++;
}
addedTime--;
totalTime++;
// call 1 minute passed event here
if (OnMinutePassed != null)
{
OnMinutePassed();
}
}
UpdateMainClockText();
}
Then there's a StatHunger class that for the time being is the only subscriber to OnMinutePassed, with this method:
public void IncreaseHunger()
{
hunger = hunger + 1 + bonus;
if (hunger == THRESHOLD_2)
{
if (OnHungry != null)
{
OnHungry();
}
}
if (hunger == THRESHOLD_4)
{
if (OnStarving != null)
{
OnStarving();
}
}
}
The OnStarving event is meant to trigger other systems (not implemented, yet), plus, since I want the game to stop whatever action you're doing when you're starving, it should ideally be able to stop the IncreaseTime method, but I can't come up with anything better than this update to the TimeManager class, which to be frank feels like a cludge:
void StopTimerFlag() //subscribed to OnStarving with this method
{
stopTimer = true;
}
public void IncreaseTime(int addedTime) //Version 2
{
if (!stopTimer)
{
while (addedTime > 0)
{
if (minutes < 60)
{
minutes++;
}
else if (hours < 23)
{
minutes = 0;
hours++;
}
else
{
hours = 0;
minutes = 0;
days++;
}
addedTime--;
totalTime++;
// call 1 minute passed event here
if (OnMinutePassed != null)
{
OnMinutePassed();
}
}
UpdateMainClockText();
}
}
This thing feels silly, plus it requires another method and another callback to reset the stopTimer flag when starvation has been tended to, which is stupid. I know I could use a ScriptableObject to create a global flag that can be read and written by both classes (that's plan B), but actions and callbacks are the point of the exercise, so I'd like to find out if there's a way to do what I'm trying to do.
Suggestions? In case this is really impossible, any other plan B/C/D, etc to achieve the goal of doing this while keeping all the classes decoupled? Thanks in advance!
Your answer
![](https://koobas.hobune.stream/wayback/20220612181513im_/https://answers.unity.com/themes/thub/images/avi.jpg)