- Home /
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)
}
to stop a function use return;
or return null;
or return default(TypeName);
, to stop a for or while use break;
, to stop a coroutine use yield break;
.
Answer by beefyt123 · Sep 17, 2016 at 07:42 AM
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.
Your answer
Follow this Question
Related Questions
C# simple delay execution without coroutine? 2 Answers
Distribute terrain in zones 3 Answers
Making a fill take exactly n seconds to complete 2 Answers