Article directory
Code to test the problem
Test the execution of some functions when Time.timeScale = 0:
using System;
using System.Collections;
using UnityEngine;
namespace Temp
{
public class TestTimeScale : MonoBehaviour
{
private bool m_openInvoke = false;
private bool m_openCoroutine = false;
[ContextMenu("恢复")]
public void RestoreTimeScale()
{
Time.timeScale = 1;
}
private void OnEnable()
{
Time.timeScale = 0;
Invoke(nameof(InvokeFunc), 1f);
StartCoroutine(IEnumeratorFunc_With_WaitForSecondsRealtime());
StartCoroutine(IEnumeratorFunc_With_WaitForSeconds());
Debug.Log($"Time.timeScale={
Time.timeScale}");
}
private void Update()
{
Debug.Log(nameof(Update));
}
private void LateUpdate()
{
Debug.Log(nameof(LateUpdate));
}
private void FixedUpdate()
{
Debug.Log(nameof(FixedUpdate));
}
private void InvokeFunc()
{
Debug.Log(nameof(InvokeFunc));
}
private IEnumerator IEnumeratorFunc_With_WaitForSecondsRealtime()
{
for (int i = 0; i < 100; i++)
{
Debug.Log(nameof(IEnumerator));
yield return new WaitForSecondsRealtime(1);
}
yield return null;
}
private IEnumerator IEnumeratorFunc_With_WaitForSeconds()
{
for (int i = 0; i < 100; i++)
{
Debug.Log(nameof(IEnumerator));
yield return new WaitForSeconds(1);
}
yield return null;
}
}
}
The running output is as follows:
in conclusion
When Time.timeScale = 0 :
- Update and LateUpdate will be executed normally.
- FixedUpdate will stop execution.
- Invoke will not be executed.
- The coroutine function body will be executed, but it may be affected by Time.timeScale depending on the different conditions of yield return . For example: WaitForSecondsRealtime , WaitForSeconds .
- Time.deltaTime = 0。
sound processing
private void OnTimeScaleChange()
{
foreach (var comp in m_allAudioSource)
{
if (!comp) {
continue;
}
if (comp.isPlaying)
{
comp.pitch = Time.timeScale;
}
}
}
appendix
[1] Unity3D Research Institute’s Time.timeScale, game pause (seventy-four)
[2] Test code