Search Unity

Adding A 1 Second Click Delay

Discussion in 'Scripting' started by TheButtaSauce, Apr 27, 2015.

  1. TheButtaSauce

    TheButtaSauce

    Joined:
    Apr 12, 2014
    Posts:
    8
    This code is placed on boxes that are destroyed when clicked. I want to add a one second delay before it's possible to click again. How would you handle this?

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class destroy : MonoBehaviour {
    6.  
    7.     void OnMouseDown () {
    8.         Destroy (gameObject);
    9.     }
    10. }
    11.  
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    I'd simply keep track of when the last click was, and put in an if-test.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class destroy : MonoBehaviour {
    4.    static float lastClickTime = -999;
    5.     void OnMouseDown () {
    6.         if (Time.time - lastClickTime < 1) return;   // too soon!
    7.         lastClickTime = Time.time;
    8.         Destroy (gameObject);
    9.     }
    10. }
    I made lastClickTime static here because it seems like you want this delay to apply even between boxes.
     
    TheButtaSauce likes this.
  3. TheButtaSauce

    TheButtaSauce

    Joined:
    Apr 12, 2014
    Posts:
    8
    Awesome. That worked out perfectly. Thank you.
     
    JoeStrout likes this.