Problem with Pause function

Hello. I created a little game based on the rhythm of a song where events appear at specific intervals.

I use this function in FixedUpdate to follow the position of my song:

songPosition = (float)(AudioSettings.dspTime - dsptimesong);
songPosition = songPosition * song.pitch;

And this function to trigger my events:

for (int i = 0; i < triggerTime.Count; i++)
{
    if (songPosition >= triggerTime[i])
    {
        eventsList[i].Trigger();
        triggerTime.Remove(triggerTime[i]);
        eventsList.Remove(eventsList[i]);
    }
}

My problem is when i try to implement a simple Pause function:

 public void Resume()
    {
        pauseMenuUI.SetActive(false);
        Time.timeScale = 1f;
        audio.Play();
        GameIsPaused = false;
    }
    void Pause()
    {
        audio.Pause();
        pauseMenuUI.SetActive(true);
        Time.timeScale = 0f;
        GameIsPaused = true;
    
    }

When i pause my game there is no problem, the game pause perfectly. But when i resume my game, multiple event Trigger at the same time. For exemple if i pause my game when the music played for 30 seconds, wait for 10 second (40 seconds total) and resume my game, all the events between 30 and 40 seconds will trigger. And i don’t understand why :hushed:.

If you can help me understand why this is happening … It would be very appreciated =)

The Unity documentation doesn’t seem to specify, but I would guess that probably AudioSettings.dspTime is not affected by Time.timeScale. You could test this by Debug.Log(AudioSettings.dspTime) at various times and watching how the values change.

I can’t be sure that would explain your test results though because you haven’t made it clear when your first two code snippets run. (Are they in Update? FixedUpdate? something else?)

Yes the first two code run in FixedUpdate and thank you for your reply.

The Debug.Log(AudioSettings.dspTime) implemented in the Update function shows that AudioSettings.dspTime continue to increase even when the game is paused.
But i stop the audio too in my pause function (audio.Pause(); ) … I suppose stopping the audio don’t stop AudioSettings.dspTime but how can i do that?

I’m not sure if you can. Based on a quick skim of the scripting API I don’t see a way to do that.

I would probably try recording how much dspTime passed while paused and adjusting the calculation of songPosition in your first snippet to subtract that amount, effectively “rewinding” the song by the paused amount. Also make sure that the code in your second snippet is wrapped inside of a check that says “if (!GameIsPaused)” so that it won’t activate any triggers during the pause itself.

Alternately you could try to use Time.time instead of AudioSettings.dspTime, but apparently that’s less accurate.

I implemented your idea of recording how much dspTime passed and it seem to be working!
Thank a lot for your support :).

1 Like