Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a class property to enable/disable timer

Tags:

c#

OK, hopefully I'm not over-complicating this. I know I can just use timer.Enabled = false or timer.Stop() to stop the timer, but I'd like to incorporate a property into my main player class which would control the timer. For instance, if my player had a bool property of "healing," I'd like for when the player's property is set to healing == true, for the timer to begin, and when the player.healing property is changed to healing == false, for the timer to stop. The reason for this is that I'd like my main game loop to continue to run while my player continues to play the game and heal, and when an action is taken in the game, or when the player reaches full health, for the timer to stop.

Currently I have a function that runs each timer tick, and evaluates whether the player is full health or not, and if so, stops the timer. However, I just think being able to flip a bool property from false to true, or vice versa, would be more useful. Any help/thoughts/advice is greatly appreciated!

like image 696
tchock Avatar asked Sep 02 '26 01:09

tchock


1 Answers

A property setter is just a function, so its pretty easy:

private bool healing = false;
public bool Healing
{
     get { return healing; }
     set
     {
         healing = value;
         if (healing)
            timer.Start();
         else
            timer.Stop();
     }
}

You want to be careful about side-effects in property setters, because if you don't actually want the logic to run every time you set the value, you need to go through a seperate function:

public bool Healing { get; set; }

public void SetHealingWithTimer(bool status)
{
     Healing = status;
     if (Healing)
         timer.Start();
     else
         timer.Stop();
}
like image 116
BradleyDotNET Avatar answered Sep 04 '26 14:09

BradleyDotNET