- Home /
Stop an OnTriggerEnter event from happening if you quickly leave the trigger.,Is there a way to cancel an OntriggerEnter function if you leave the trigger quick enough?
I am creating a digging game for my class where you control a drill and dig through blocks of dirt. I am trying to make it so if you drill into a block of dirt for x amount of seconds, you will destroy the block. However, I want to make it so that if you quickly stop drilling the block, it will stop digging and not destroy the block. Right now, I have a timer that delays the destruction of the block, however, if you are not colliding with the trigger after the timer runs out, it still destroys the block. Any help would be appreciated, thanks!
public class AttackTrigger : MonoBehaviour
{
public float digTimer;
private bool timerOn = false;
private void Start()
{
}
private void Update()
{
if (timerOn == true)
{
digTimer -= Time.deltaTime;
}else if (timerOn == false)
{
digTimer = 1.0f;
}
}
IEnumerator OnTriggerEnter2D(Collider2D other)
{
timerOn = true;
yield return new WaitForSeconds(1);
if (other.tag == "Ground" && digTimer <= 0)
{
Destroy(other.gameObject);
timerOn = false;
}
}
try this function:
void OnTriggerExit2D(Collider2D other)
{
timerOn = false;
}
Answer by tormentoarmagedoom · Oct 06, 2019 at 07:56 PM
Hello There.
Then, make it diferent.
In the OnTriggerEnter2D, you activate a IEnumerator (Coroutine) function with just a yield of 1 second.
After that yield, a Input detector. If user is still pressing the buton, it destroys the block.
Simple and easy!
Bye!
Answer by Mouton · Oct 06, 2019 at 09:45 PM
Add OnTriggerExit2D event in your class. From this method, set a bool to True. In the OnTriggerEnter2D event, just after the yield, check if the bool is set to true, if it is, abort the digging.
Your answer
Follow this Question
Related Questions
Why is this rigidbody not activating the trigger? 0 Answers
Is there anyway to make an object impenetrable? 1 Answer
How to destroy bullet upon colliding with another object instead of bouncing off of it 3 Answers
Physics2D.OverlapCircle dont detect triggers 3 Answers
Can't call Destroy() on two objects 0 Answers