Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Idle counter.

Discussion in 'Scripting' started by olenedgar, Jun 10, 2015.

  1. olenedgar

    olenedgar

    Joined:
    Nov 3, 2014
    Posts:
    3
    Hello,

    I am trying to make an idle counter that triggers an action if no user keyboard or mouse input has been detected for a certain amount of time. If there is user input before the timer runs out, I would like the timer to reset without performing the action.

    I did a search and found a script but unfortunately for me, it does not reset the counter if there is user input before the timer runs out.

    Any ideas?
    Thanks.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ParticleColor : MonoBehaviour {
    5.  
    6.     public bool idle = false;
    7.     public float timeToIdle = 2.0f;  // 2 seconds
    8.     float currentTime = 0f;
    9.        
    10.     void Start () {
    11.         currentTime = Time.time + timeToIdle;
    12.     }
    13.  
    14.     void Update () {
    15.        
    16.         if(Input.anyKey == false )
    17.         {
    18.             checkIdle();
    19.         }
    20.     }
    21.    
    22.     void checkIdle()
    23.     {
    24.         if(Time.time > currentTime)
    25.         {
    26.             idle = true;
    27.  
    28.             // perform action
    29.  
    30.             this.GetComponent<ParticleSystem>().startColor = new Color(Random.value, Random.value, Random.value);
    31.             print("No input, change color");
    32.  
    33.             currentTime = Time.time + timeToIdle;
    34.         }
    35.  
    36.     }
    37. }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you just need an else clause for the if in update which has the exact same line of code as in the start function...
     
    olenedgar likes this.
  3. olenedgar

    olenedgar

    Joined:
    Nov 3, 2014
    Posts:
    3
    Yep, solved it!
    Thank you!