Search Unity

How to make a repeat timer C#

Discussion in 'Getting Started' started by phantomunboxing, Mar 20, 2016.

  1. phantomunboxing

    phantomunboxing

    Joined:
    Nov 10, 2015
    Posts:
    43
    I just want a timer that repeats itself every x seconds... for example every 5 seconds take 1 from hunger variable
     
  2. MikeTeavee

    MikeTeavee

    Joined:
    May 22, 2015
    Posts:
    194
    There are many many ways to do this. One way is to use InvokeRepeating.

    In this sample code, Starve is called for the first time after 5 seconds, and then every 1 second after that.

    Code (CSharp):
    1.    public int hunger;
    2.  
    3.     void Start() {
    4.         InvokeRepeating("Starve", 5, 1);
    5.     }
    6.    void Starve() {
    7.         hunger--;
    8.     }
    9.  
    10. }
     
    Last edited: Mar 20, 2016
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Yep, that's a reasonable way. Here's another.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Hunger : MonoBehaviour {
    4.     public int hunger;
    5.    
    6.     public float nextTime;
    7.    
    8.     void Update() {
    9.         if (Time.time > nextTime) {
    10.             hunger--;
    11.             nextTime = Time.time + 1;
    12.         }
    13.     }  
    14. }
     
    OboShape and Ryiah like this.
  4. narhw4l

    narhw4l

    Joined:
    Aug 6, 2021
    Posts:
    2
    @MikeTeavee THANK YOU SO MUCH. I was looking and trying to get some code to work for 6 hours now. I stumbled upon your response, and it was a lifesaver since I'm using this for a 48-hour jam.
    Code (CSharp):
    1.     void Start()
    2.     {
    3.         bladeSpinning = bladeH.GetComponent<BladeSpinning>();
    4.         coinCount = 0;
    5.         if(bladeSpinning.paused == false)
    6.         {
    7.             InvokeRepeating("AddingCoins", 0, 0.2f);
    8.         }
    9.     }
    10.  
    11.     void AddingCoins()
    12.     {
    13.         coinCount += coinLevel;
    14.         coinText.text = coinCount.ToString();
    15.     }