提问者:小点点

受时间刻度影响的协程WaitForSeconds


我正在为我的UI元素制作一个简单的动画。

我有一个动画组件,它有2个不同的动画-ZoomIn和ZoomOut。

每当需要在屏幕上显示UI元素(如按钮)时,就会显示这些动画。

我通常更喜欢在不显示时停用游戏对象。

我为动画编写了以下方法:

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 WaitForSeconds (0.5f);
        } else if(gameObj.activeSelf == true) {
            gameObjectAnimator.SetTrigger ("ZoomOut");
            yield return new WaitForSeconds (0.5f);
            gameObj.SetActive (false);   // code not execute when timescale = 0
        }
        yield return null;
}

对于大多数屏幕,代码工作正常,但当我使用timescale=0暂停游戏时,代码显示问题。

当时间刻度为0时,线gameObj。SetActive(false)不工作。


共1个答案

匿名用户

我知道可能有点晚了,但是:

问题不在于SetActive,而在于WaitForSecondssi受时间的影响。时间刻度

实际暂停时间等于给定时间乘以Time.timeScale。如果希望使用未缩放时间等待,请参见WaitFor秒dsRealtime

所以如果你有时间。timescale=0等待秒将永远不会结束!

你应该使用WaitFor秒dsRealtime

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;
}