Timer for repeated action

I have a really nice light bulb with a switch somewhere in the scene that turns the scene into a dark room (using a black texture with alpha). All works just fine. However, I want to implement the following behaviour - if the player turns on and off the light quickly for several times, the light bulb should explode. I use a simple toggle script to control what happens when the light is on or off.

Any ideas?! Thanks!

You can count how many times the player turned the light off and on and store that value into a counter. Then you have a coroutine that resets the counter every N seconds.

You can check the value of the counter. If it reaches a certain value, you trigger the explosion event.

Here is a script stub for such a timed counter:

public class TimedCounter : MonoBehaviour
{
    public float startTimeOffset;
    public float resetDelay;

    public int Count
    {
        get;
        private set;
    }

    void Start()
    {
        InvokeRepeating("ResetCounter", startTimeOffset, resetDelay);
    }

    public void ResetCounter()
    {
        this.Count = 0;
    }

    public void IncrementCounter()
    {
        this.Count += 1;
    }
}

Ok, it was easier than I thought; Now if you mess around with a switch at a higher rate the effect is, well, as desired :slight_smile:

			if (hit.collider.tag == "LightBulb")
				{
					if ((Time.time - lastTapTime) < tapSpeed)
						{
							Debug.Log("Destroyed!");
							LIGHTON.SetActiveRecursively (false);
							LIGHTOFF.SetActiveRecursively (true);
							LightSwitchControler.active = false;
							LightSwitchControlerDummy.active = true;
							GameObject.Find("MainCamera").SendMessage("LightRoom");
						}
						lastTapTime = Time.time;
				}