试图通过脚本暂停动画,但它在状态之间闪烁

Trying to pause animation through scripting, but it flickers between states instead

我有一些代码可以在 UI 的一部分处于活动状态时暂停动画

public void Update()
{
    if (tutorialModal.activeInHierarchy == true)
    {
        Debug.Log("The tutorial panel is active!!");
        nac.UserClickedPauseButton();
    }
    else
    {
        Debug.Log("The tutorial panel is not active, I repeat NOT ACTIVE!");
    }
}

UserClickedPauseButton代码如下

public void UserClickedPauseButton()
{
    if (animator.speed > 0f)
    {
        // we need to pause animator.speed
        rememberTheSpeedBecauseWeMightNeedIt = animator.speed;
        animator.speed = 0f;
        playImage.gameObject.SetActive(true);
        pauseImage.gameObject.SetActive(false);

    }
    else
    {
        // we need to "unpause"
        animator.speed = rememberTheSpeedBecauseWeMightNeedIt;
        playImage.gameObject.SetActive(false);
        pauseImage.gameObject.SetActive(true);
    }
}

现在,当 GUI 元素处于活动状态时,动画不会暂停,它会在暂停和未暂停之间闪烁。

我只想让背景动画在教程打开时暂停。

您需要添加 paused 布尔变量。否则,当 tutorialModal 处于活动状态时,会在每一帧上调用 UserClickedPauseButton()

bool paused = false;

public void Update()
{
    if (tutorialModal.activeInHierarchy == true && !paused)
    {
        Debug.Log("The tutorial panel is active!!");
        nac.UserClickedPauseButton();
        paused = true;
    }
    else if(tutorialModal.activeInHierarchy == false && paused)
    {
        Debug.Log("The tutorial panel is not active, I repeat NOT ACTIVE!");

        // And remember to call UserClickedPauseButton here too, 
        // so animation is unpaused when tutorialModal is not active.
        nac.UserClickedPauseButton(); 

        paused = false;
    }
}