Using a class property to enable / disable a timer

Ok, I hope I'm not over complicating this. I know I can just use timer.Enabled = false or timer.Stop () to stop the timer, but I would like to include a property in my main player class that will control the timer. For example, if my player had a "heal" bool property, I would like when the player property is set to heal == true to start the timer and when the player.healing property is changed to heal = = false for the timer to stop. The reason for this is because I want my main game loop to keep running 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 a timer to stop.

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

+3


source to share


3 answers


The properties attribute is just a function, so it's 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 really want the logic to run every time you set a value, you have to pass a separate function:

public bool Healing { get; set; }

public void SetHealingWithTimer(bool status)
{
     Healing = status;
     if (Healing)
         timer.Start();
     else
         timer.Stop();
}

      

+5


source


Can't do this:



private Timer timer;

public bool Healing
{
    get
    {
        return timer.Enabled;
    }
    set
    {
        timer.Enabled=value;
    }
}

      

+2


source


There is nothing wrong with starting the timer after the player is fully healthy. Just put a cap on your maximum health i.e.

if(health < maxHealth)
{
    healing = true;
    health += healthModifier;
}
else
{       
    healing = false;        
}

//fix health meter, if above maximum
if(health > maxHealth)
{
    health = maxHealth;
}

      

It's also more flexible because you can later assign a temporary maximum health boost that will depend on another timer (for example).

+1


source







All Articles