askvity

How to get current time in Unity C#?

Published in Unity Time Management 6 mins read

In Unity C#, you can obtain time information in several ways, depending on whether you need in-game time, the user's system time, or accurate real-world time fetched from an external source like an API.

Getting Time in Unity C

Choosing the right method depends entirely on your game's requirements. Here are the primary approaches:

1. In-Game Time

Unity's built-in Time class provides various properties related to the game's internal clock, which is affected by Time.timeScale.

  • Time.time: The time in seconds since the start of the game. This is affected by Time.timeScale.
  • Time.unscaledTime: The time in seconds since the start of the game, not affected by Time.timeScale. Useful for UI elements or actions that should proceed regardless of game speed.
  • Time.deltaTime: The time in seconds it took to complete the last frame. Useful for frame-rate independent movement or timing. Affected by Time.timeScale.
  • Time.unscaledDeltaTime: The time in seconds it took to complete the last frame, not affected by Time.timeScale.

Example:

using UnityEngine;

public class GameTimer : MonoBehaviour
{
    void Update()
    {
        // Log the time since the game started (affected by timeScale)
        Debug.Log("Current Game Time: " + Time.time);

        // Log the time since the game started (not affected by timeScale)
        Debug.Log("Current Unscaled Game Time: " + Time.unscaledTime);
    }
}

2. User's System Time (Real-World)

To get the actual date and time from the user's computer or device, you can use the standard .NET System.DateTime struct.

  • System.DateTime.Now: Returns a DateTime object representing the current date and time on the local computer.
  • System.DateTime.UtcNow: Returns a DateTime object representing the current date and time in Coordinated Universal Time (UTC).

Example:

using System;
using UnityEngine;

public class SystemTimeDisplay : MonoBehaviour
{
    void Start()
    {
        // Get the current local system time
        DateTime currentLocalTime = System.DateTime.Now;
        Debug.Log("Current Local System Time: " + currentLocalTime.ToString());

        // Get the current UTC system time
        DateTime currentUtcTime = System.DateTime.UtcNow;
        Debug.Log("Current UTC System Time: " + currentUtcTime.ToString());
    }
}
  • Note: System.DateTime.Now relies on the user's system clock, which they can potentially change. This method is not reliable for applications requiring accurate, tamper-proof real-world time (e.g., online games, timed events).

3. Real-World Time from an API (Reliable)

For reliable, accurate real-world time that isn't dependent on the user's potentially incorrect system clock, you can fetch time from an external time server or API over the internet.

As mentioned in the provided reference, you would need to use Unity's networking capabilities. "We need to be using Unity. Engine. Networking. Now we can create a new Unity Web request. And use Weber request dot get with the API URL to get the value to actually send the web request."

This involves:

  1. Include the necessary namespace: using UnityEngine.Networking;.
  2. Create a UnityWebRequest object.
  3. Use UnityWebRequest.Get(api_url) where api_url is the address of a service that provides the current time (e.g., a dedicated time API or a general web service that includes time info).
  4. Send the web request asynchronously.
  5. Process the response to extract the time information.

Example (Conceptual):

using UnityEngine;
using UnityEngine.Networking; // Required namespace
using System.Collections;
using System; // Required for DateTime processing

public class ApiTimeFetcher : MonoBehaviour
{
    // Example API URL (You need a real time API endpoint)
    private string timeApiUrl = "https://worldtimeapi.org/api/ip"; // Example using worldtimeapi

    void Start()
    {
        StartCoroutine(GetTimeFromApi());
    }

    IEnumerator GetTimeFromApi()
    {
        // Create a new Unity Web request using the API URL
        using (UnityWebRequest webRequest = UnityWebRequest.Get(timeApiUrl))
        {
            // Send the web request
            yield return webRequest.SendWebRequest();

            if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError("Error fetching time: " + webRequest.error);
            }
            else
            {
                // Request successful, process the response
                string jsonResponse = webRequest.downloadHandler.text;
                Debug.Log("Received time data: " + jsonResponse);

                // You would typically parse the JSON response here to extract the time.
                // Example (simplified, depends on API format):
                // WorldTimeApi response contains "utc_datetime"
                try
                {
                    // A JSON parsing library like JsonUtility or Newtonsoft.Json is needed for real parsing
                    // This is a very simplified example assuming a specific format
                    // You'd search for the time field and parse it.
                    // Example using string manipulation (not robust):
                    int startIndex = jsonResponse.IndexOf("\"utc_datetime\":\"") + "\"utc_datetime\":\"".Length;
                    int endIndex = jsonResponse.IndexOf("\"", startIndex);
                    if (startIndex > 0 && endIndex > startIndex)
                    {
                        string timeString = jsonResponse.Substring(startIndex, endIndex - startIndex);
                        DateTime apiTime = DateTime.Parse(timeString); // Parse the extracted string
                        Debug.Log("Current UTC Time from API: " + apiTime.ToString("yyyy-MM-dd HH:mm:ss UTC"));
                    } else {
                         Debug.LogError("Could not parse time from API response.");
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("Failed to parse API response: " + e.Message);
                }
            }
        }
    }
}
  • Note: This method requires an internet connection and involves asynchronous operations (StartCoroutine or async/await). The complexity depends on the API format (often JSON) and requires parsing the response.

Summary of Methods

Here’s a quick comparison:

Method Source Reliability Requires Internet Affected by TimeScale Use Case
Time Class Game Engine N/A (Game Time) No Yes (Time.time) Game logic, timers, animations
System.DateTime User's System Low (Can be changed) No No Displaying local time, saving timestamps
API Request External Server High (Accurate) Yes No Accurate real-world time, online events

Choose the method that best fits whether you need game progression time, the user's local time, or a globally accurate, reliable real-world time.

Related Articles