[Solved] How To Slow Down My Timer Script?

Hi there a simple question how do I slow down my timer? I have got this script here but goes up way to fast! Preferably like in seconds. Can someone advise me how I can control the speed it goes up. Thank you very much.

using UnityEngine;
using System.Collections;

public class Timer : MonoBehaviour
{

    private GUISkin skin;
    double timer = 0.0;
    public static int Score = 0;

    // Use this for initialization
    void Start () {
       
        // Load a skin for the buttons
        skin = Resources.Load("GUISkin") as GUISkin;
    }
   
    // Update is called once per frame
    void Update () {
       
        timer += Time.deltaTime;

        Score += (int)timer;
       
    }
   
    void OnGUI()
    {
        // Set the skin to use
        GUI.skin = skin;
       
        GUI.Box (new Rect(40,20,80,40), Score.ToString () );
       
       
    }
   
}

The easiest way is with a coroutine:
in start function:
StartCoroutine(changeScoreByTime());

IEnumerator changeScoreByTime(){
while(true){
yield return new WaitForSeconds(1.0f);
{ Score ++;
}
}

You would delete what’s in the update, or comment it out at first in case there are problems.

1 Like

Your code doesn’t look far off. Your “timer” variable is basically the value you’re after. It should contain the total time (in seconds) since the game started - but as a double. So, you don’t want to add that value to your Score in every frame. Instead, Score should simply be that value, only (apparently) converted to an INT. So, I’d think this minor change would do what you want.

void Update()
{
    timer += Time.deltaTime;
    Score = (int)timer;
}

Note the “Score =” instead of “Score +=”

Jeff

1 Like

You could also define a value storing your next “tick” time, when Time.time is greater then said value run some function and increment the value to a future time

private float NextTickTime;

void Update()
{
   if(Time.time >= NextTickTime)
   {
     score += amount;
     NextTickTime = Time.time + 1;
   }
}

The if conditional will check every frame, though only execute once per second.

1 Like

Thank you very much for the speedy response. Looking at it right now it was a very easy fix. Thank you again.