关于Unity中使用timeScale暂停的一些注意要点

  • Time.timeScale = 0可以暂停游戏,Time.timeScale = 1恢复正常。暂停内容包含动画,特效,UI动画等涉及使用到

  • 设置Time.timeScale = 0 将会暂停所有和帧率无关的事情。这些主要是指所有的物理事件和依赖时间的函数、刚体力和速度等,而且FixedUpdate会受到影响,会被暂停(不是Update),即timeScale =0 时将不会调用FixedUpdate函数了。timeScale不会影响Update和LateUpdate的执行速度。因为FixedUpdate是根据时间来的,所以timeScale只会影响FixedUpdate的速度。

  • 如果游戏暂停以后想在暂停界面上继续播放一些不受Time.timeScale 影响的动画或者粒子特效之类的,那么我们就需要用到Time.realtimeSinceStartup去单独恢复他们,还有声音部分也需要单独恢复timeScale

如何让游戏中某个游戏对象不受Time.timeScale影响

  • 动画(Animations ignore TimeScale - Unity Answers)
static IEnumerator Play( Animation animation, string clipName, bool useTimeScale,System.Action onComplete )
	{
		if(!useTimeScale)
		{
			AnimationState _currState = animation[clipName];
			bool isPlaying = true;
			float _startTime = 0F;
			float _progressTime = 0F;
			float _timeAtLastFrame = 0F;
			float _timeAtCurrentFrame = 0F;
			float deltaTime = 0F;
			animation.Play(clipName);
			_timeAtLastFrame = Time.realtimeSinceStartup;
			while (isPlaying) 
			{
				_timeAtCurrentFrame = Time.realtimeSinceStartup;
				deltaTime = _timeAtCurrentFrame - _timeAtLastFrame;
				_timeAtLastFrame = _timeAtCurrentFrame; 
				
				_progressTime += deltaTime;
				_currState.normalizedTime = _progressTime / _currState.length; 
				animation.Sample ();
				if (_progressTime >= _currState.length) 
				{
					if(_currState.wrapMode != WrapMode.Loop)
					{
						isPlaying = false;
					}
					else
					{
						_progressTime = 0.0f;
					}
				}
				yield return new WaitForEndOfFrame();
			}
			yield return null;
			if(onComplete != null)
			{
				onComplete();
			} 
		}
		else
		{
			animation.Play(clipName);
		}
	}
  • 粒子特效不受timescale影响(https://gist.github.com/AlexTiTanium/5676482)
using UnityEngine;
using System.Collections;
 
public class ParticaleAnimator : MonoBehaviour {
  
	private void Awake()
	{
		particle = GetComponent();
	}
 
	// Use this for initialization
	void Start ()
	{
		lastTime = Time.realtimeSinceStartup;
	}
	
	// Update is called once per frame
	void Update () 
	{
		
		float deltaTime = Time.realtimeSinceStartup - (float)lastTime;
 
        	particle.Simulate(deltaTime, true, false); //last must be false!!
 
        	lastTime = Time.realtimeSinceStartup;
	}
 
	private double lastTime;
	private ParticleSystem particle;
 
}
  • 声音忽略影响
AudioSource source = gameObject.AddComponent();
//设置播放声音的速度。 默认速度是1 ,那如果我们加速了,那就应该是 Time.timeScale
source.pitch =IgnoreTimeScale?1:Time.timeScale;
//播放声音
source.Play();

 遍历所有音频对象

    public static void TimeScaleChanged()
    {
		foreach (AudioSource source in soundList.Keys)  
		{  
			if(source != null)
			{
				source.pitch =	soundList[source]?1:Time.timeScale;
			}
		}  
    }

你可能感兴趣的:(Unity,unity,c++)