Unity3d tests the case of Time.timeScale = 0

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:
Insert image description here

in conclusion

When Time.timeScale = 0 :

  1. Update and LateUpdate will be executed normally.
  2. FixedUpdate will stop execution.
  3. Invoke will not be executed.
  4. 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 .
  5. 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

Guess you like

Origin blog.csdn.net/WGYHAPPY/article/details/130608322