Pro*_*Das 3 c# coroutine unity-game-engine
我正在为我的 UI 元素制作一个简单的动画。
我有一个动画组件,它有 2 个不同的动画 - ZoomIn 和 ZoomOut。
每当需要在屏幕上显示 UI 元素(例如按钮)时,就会显示这些动画。
我通常更喜欢在不显示时停用游戏对象。
我为动画编写了以下方法:
私人 IEnumerator ToggleObjectWithAnimation (GameObject gameObj) { Animator gameObjectAnimator = gameObj.GetComponent(); // Animator 设置为未缩放时间 如果(gameObj.activeSelf == false){ gameObj.transform.localScale = new Vector3 (0, 0, 1.0f); gameObj.SetActive (true); gameObjectAnimator.SetTrigger("ZoomIn"); yield return new WaitForSeconds (0.5f); } else if(gameObj.activeSelf == true) { gameObjectAnimator.SetTrigger("ZoomOut"); yield return new WaitForSeconds (0.5f); gameObj.SetActive (false); // 当时间刻度 = 0 时代码不执行 } 收益率返回空; }
该代码在大多数屏幕上都可以正常工作,但是当我使用 timescale = 0 暂停游戏时会出现问题。
当 timescale 为 0 时,gameObj.SetActive (false) 行不起作用。
我知道可能有点晚了,但是:
问题不在于 ,SetActive
而是WaitForSeconds
si 受Time.timeScale
!
实际暂停时间等于给定时间乘以
Time.timeScale
。查看WaitForSecondsRealtime
您是否希望使用未缩放的时间进行等待。
所以,如果你有Time.timescale=0
在WaitForSeconds
永远不会结束!
你应该使用 WaitForSecondsRealtime
private IEnumerator ToggleObjectWithAnimation (GameObject gameObj)
{
Animator gameObjectAnimator = gameObj.GetComponent (); // Animator is set to unscaled time
if (gameObj.activeSelf == false)
{
gameObj.transform.localScale = new Vector3 (0, 0, 1.0f);
gameObj.SetActive (true);
gameObjectAnimator.SetTrigger ("ZoomIn");
yield return new WaitForSecondsRealtime(0.5f);
}
else if(gameObj.activeSelf == true)
{
gameObjectAnimator.SetTrigger ("ZoomOut");
yield return new WaitForSecondsRealtime(0.5f);
gameObj.SetActive (false); // code not execute when timescale = 0
}
yieldr eturn null;
}
Run Code Online (Sandbox Code Playgroud)