Reputation: 161
I'm trying to reduce a float by a time value, i'm using Unity and stopping time Time.timeScale = 0f;
so can not use Time.deltaTime
so using 'Time.realtimeSinceStartup' in a while loop, i read in the master volume variable from a global script that the player can set in game between 0 - 1 so say i read in 0.6 and i want to lower the volume to 0 in 2 second how do i get the percentage to keep reducing the volume by ?
Here is my code ..
private IEnumerator VolumeDown ()
{
float volumeIncrease = globalVarsScript.musicVolume;
float volumePercentage = ??;
float newLerpEndTime = Time.realtimeSinceStartup + 2f;
while (Time.realtimeSinceStartup < newLerpEndTime)
{
audio.volume = volumeIncrease;
volumeIncrease -= volumePercentage;
yield return null;
}
}
Sorry i just can't get the 'volumePercentage'
Thanks.
Upvotes: 4
Views: 7293
Reputation: 125415
I'm using Unity and stopping time
Time.timeScale = 0f;
so can not useTime.deltaTime
so using 'Time.realtimeSinceStartup' in a while loop.
You don't need to use Time.realtimeSinceStartup
for this. It is true that setting Time.timeScale
to 0 makes Time.deltaTime
to return 0 every frame.
This is why Time.unscaledDeltaTime
was added in Unity 4.5 to address that. Simply replace the Time.deltaTime
with Time.unscaledDeltaTime
. You can event use if (Time.timeScale == 0)
to automatically decide whether to use Time.unscaledDeltaTime
or Time.deltaTime
.
IEnumerator changeValueOverTime(float fromVal, float toVal, float duration)
{
float counter = 0f;
while (counter < duration)
{
if (Time.timeScale == 0)
counter += Time.unscaledDeltaTime;
else
counter += Time.deltaTime;
float val = Mathf.Lerp(fromVal, toVal, counter / duration);
Debug.Log("Val: " + val);
yield return null;
}
}
Usage:
StartCoroutine(changeValueOverTime(5, 1, 3));
The value changes from 5
to 1
within 3
seconds. It doesn't matter if Time.timeScale
is set to 1
or 0
.
Upvotes: 9