C# Timer for Bolt & Unity

Creating a timer in bolt wasn’t working for me so I wrote a script for it and then just integrated it with Bolt variables.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Bolt;

public class StopWatch : MonoBehaviour
{

    public Text text;
    float theTime;
    public float speed = 1;
    

    // Use this for initialization
    void Start()
    {
        //text = GetComponent(-INSERT LESS THAN SIGN -)Text(-INSERT GREATER THAN SIGN -)();
    }

    // Update is called once per frame
    void Update()
    {
    
        if ((bool)Variables.ActiveScene.Get("Timer_Running") == true)
        {
            theTime += Time.deltaTime * speed;
            string hours = Mathf.Floor((theTime % 216000) / 3600).ToString("00");
            string minutes = Mathf.Floor((theTime % 3600) / 60).ToString("00");
            string seconds = (theTime % 60).ToString("00");
            text.text = hours + ":" + minutes + ":" + seconds;
        }
    }

    public void ClickPlay()
    {
        
        Variables.ActiveScene.Set("Timer_Running", true);
    }

    public void ClickStop()
    {
        Variables.ActiveScene.Set("Timer_Running", false);
    }


}

You need to create two scene based variables.

  • theTime
  • Timer_Running

This script puts the timer in the text area on the UI. Just drag and drop this script onto an object in the scene and then drag and drop a text box into the variables area of the script, and you will be up and running. This time is great for timed games and in LMS software to see how long content takes to complete.

Count Down Timer

Here is a countdown timer pretty much working on the same variables

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Bolt;

public class CountDown : MonoBehaviour
{
    public float timeRemaining = 10;
    public bool timerIsRunning = false;
    public Text timeText;

    private void Start()
    {
        // Starts the timer automatically
        timerIsRunning = true;
    }

    void Update()
    {
        if ((bool)Variables.ActiveScene.Get("Timer_Running") == true)
        {
            if (timeRemaining > 0)
            {
                timeRemaining -= Time.deltaTime;
                DisplayTime(timeRemaining);
            }
            else
            {
                Debug.Log("Time has run out!");
                timeRemaining = 0;
                timerIsRunning = false;
                Variables.ActiveScene.Set("Timer_Running", false);
                Variables.ActiveScene.Set("Time_Out", true);
            }
        }
    }

    void DisplayTime(float timeToDisplay)
    {
        timeToDisplay += 1;

        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);

        timeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}

Leave a Reply