Disable collider for 2 seconds

50 views Asked by At

I'm using this script on a cube to detect out of bound colliding and alerting user:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PixelCrushers.DialogueSystem;

public class OutOfBounds : MonoBehaviour
{
    public string message;

    void Start(){
        gameObject.GetComponent<Renderer>().enabled = false;
    }

    void OnCollisionEnter(Collision collision) {
        if (collision.gameObject.tag == "Player") {
            DialogueManager.ShowAlert(message);
        }
    }

}

This is working fine but its showing many alerts at once.

How can I make show just one alert for a while, like 2 seconds?

1

There are 1 answers

0
Aincvy On

Use a timestamp.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PixelCrushers.DialogueSystem;

public class OutOfBounds : MonoBehaviour
{
    public string message;
    public float alertCooldown = 2f;
    private float nextAlertTime = 0;

    void Start(){
        gameObject.GetComponent<Renderer>().enabled = false;
    }

    void OnCollisionEnter(Collision collision) {
        float now = Time.time;
        if (now < nextAlertTime) {
          return;
        }
        nextAlertTime = now + alertCooldown;

        if (collision.gameObject.tag == "Player") {
            DialogueManager.ShowAlert(message);
        }
    }

}