If condition is not true, stop timer and reset.

Hello! What I’m trying to do is create a block hardness script using a timer. Originally I was using a float variable that would be decreased when mined, but if a computer has a higher FPS it ends up mining really fast. I thought I could try using a timer. This is where I’m getting stuck. I can’t get the timer to stop when I’m not mining the block. It just keeps going regardless of whether I’m still mining. I want it so that the timer only runs when I’m mining the block. If I’m mining and then suddenly stop before the timer is up, I want it to reset, and not run again until I mine again.

I’ve tried coroutine, I’ve tried timers, but it just doesn’t seem to work. I don’t get why it is so hard to simply stop a timer if a certain condition is not true.

Here’s some of my block destruction code, the code with a variable being subtracted:

hit.collider.gameObject.GetComponent<BlockProp>().strength = hit.collider.gameObject.GetComponent<BlockProp>().strength - drillStrength;

if (hit.collider.gameObject.GetComponent<BlockProp>().strength <= 0) {
(destroys block in here, code here not neccesary)
}

Hey I just tried this script out for you. From what I understand of your original question it should do what you want. You will need to change it to match what your needs.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimerResetScript : MonoBehaviour {

    float strength = 10;

    public bool isBeingMined;

    void OnMouseDown()
    {
        //When mouse clicks on block sets bool to true and starts the Coroutine
        isBeingMined = true;
        StartCoroutine(mineBlock());
    }

    void OnMouseUp()
    {
        //When mouse is released sets bool to false and stops the Coroutine
        isBeingMined = false;
        StopCoroutine(mineBlock());
    }

    IEnumerator mineBlock()
    {
        //Checks to see is the bool is true and if so increment its strength down.
        while (isBeingMined)
        {
            if (strength > 0)
            {
                strength = strength - Time.deltaTime;
                Debug.Log("strength: " + strength);

            }
            else if (strength <= 0)
            {
                Destroy(this.gameObject);
            }
            yield return null;
        }
        yield return null;
    }
}

It doesn’t reset the timer but it will just stop reducing the strength of the block while the player is holding the mouse button down.