- Home /
Time not accurate?
I'm working on a music game, so I need to be able to accurately sync the music with what's going on in the game. And it all works as long as nothing too taxing is going on in the scene. But there are times when Unity's time seems to slow down when the frame rate can't keep up. For example, if I play a 3.5 minute song (210 seconds long), if I log the current Unity time and start a separate stop watch when the song starts, when it ends, the stop watch will correctly show 3.5 minutes have passed, but based on the Unity logs, only 190 seconds or so will have passed.
I'm guessing Unity is limiting the max delta time allowed between frames? Is there a way to turn that off so I can keep an accurate time?
What time resolution do you need (seconds, milliseconds, ??). Depending on your requirements, there are other Time members that might suit you. Also, maybe there's something wrong in your code? If you can paste the relevant code here, you'll likely get some more targeted input.
A 3.5 $$anonymous$$ute song is 210 seconds, so both your recorded ti$$anonymous$$gs are miles out. Please show the code you're using - there's definitely a mistake somewhere to be getting errors of that magnitude.
Yea, yea. It was still 190 seconds vs 210 seconds.
Answer by Plattinator · Jun 26, 2016 at 06:02 AM
Not sure about the Unity time going slower than real-time, but if you're using an AudioSource to play your music, you can get the current playback time of the AudioSource through AudioSource.time. That should allow you to get the exact time for where you're at in the music to sync up with the game.
I've been using this where I can to combat the problem, but objects still move based on Time.deltaTime. AudioSource doesn't have a deltaTime. Though, maybe I could try calculating my own based on the AudioSource's time.
Answer by Mindmapfreak · Jun 26, 2016 at 09:41 PM
You could try to use the Stopwatch-class and see if it is more accurate in your case.
using UnityEngine;
using System.Collections;
using System;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
public class StopwatchTest : MonoBehaviour {
private Stopwatch stopwatch;
// Use this for initialization
void Start () {
this.stopwatch = new Stopwatch();
this.stopwatch.Start();
if(Stopwatch.IsHighResolution)
{
Debug.Log("The stopwatch is high resolution");
}
}
// Update is called once per frame
void Update () {
float elapsedSeconds = ((float)this.stopwatch.ElapsedMilliseconds)/1000.0f;
Debug.Log(Time.time+" vs "+ elapsedSeconds);
}
}
Your answer

Follow this Question
Related Questions
Problem Min and Max Time 1 Answer
fuel compsumation 0 Answers
Force mode and delta timing 1 Answer
How can I match up some code and an animation keyframe 0 Answers
When to use Time.deltaTime? 3 Answers