create a timer script for unity in csharp

To create a timer script for Unity in C#, you can use the Time class in Unity. Here's an example script that will create a timer that counts down from a specified amount of time:

main.cs
using UnityEngine;

public class Timer : MonoBehaviour
{
    // The amount of time the timer will count down from
    public float totalTime = 30f;

    // The current time remaining on the timer
    private float currentTime;

    void Start()
    {
        // Set the initial time remaining to the total time specified
        currentTime = totalTime;
    }

    void Update()
    {
        // Update the timer by subtracting the time since the last frame from the current time remaining
        currentTime -= Time.deltaTime;

        // If the timer has run out, do something (in this case, just print to the console)
        if (currentTime <= 0f)
        {
            Debug.Log("Timer has run out!");
        }
    }
}
726 chars
29 lines

In this script, the totalTime variable specifies the amount of time the timer will count down from, and the currentTime variable keeps track of the current time remaining on the timer. In the Start() method, the initial time remaining is set to the totalTime value specified. In the Update() method, the timer is updated by subtracting the time since the last frame (accessed through the Time.deltaTime property) from the current time remaining. When the timer runs out (i.e. the currentTime value is less than or equal to 0f), something (in this case, just printing to the console) can be done.

gistlibby LogSnag