简单的协程动画脚本破坏了统一

Simple Coroutine Animation script breaks unity

好吧,所以我使用协程等待 6 秒,然后执行一个方法来更改动画师中的浮点数,非常简单的东西。我的问题是当我将它放在游戏对象上时,此脚本中的某些内容导致我的统一编辑器完全锁定,我不知道为什么。我不认为我有任何无限循环,但我不确定。谁有想法?提前谢谢。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class handanimatordock : MonoBehaviour
{

    public Animator hand;
    private float Blendfloat;
    bool ChangeHand = false;
    private float timefloat = 0.0f;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(waiter());
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void changeHands()
    {

        if (ChangeHand == false)
        {
            ChangeHand = true;

            while (Blendfloat != 1.0f)
            {
                Blendfloat = Blendfloat + 0.01f;
                hand.SetFloat("Blend", Blendfloat);
            }

        }
        else
        {

            ChangeHand = false;

            while (Blendfloat != 0.0f)
            {
                Blendfloat = Blendfloat - 0.01f;
                hand.SetFloat("Blend", Blendfloat);
            }

        }

    }


    IEnumerator waiter()
    {
        

        //Wait for 4 seconds
        yield return new WaitForSeconds(6);
        changeHands();
        StartCoroutine(waiter());
    }


}

你可能有一个无限循环

while (Blendfloat != 1.0f)
{
    Blendfloat = Blendfloat + 0.01f;
    hand.SetFloat("Blend", Blendfloat);
}

从不 使用 ==!=.

直接比较两个 float

由于浮点印象,值类似于

10f * 0.1f  

可能最终会成为 1.0000000010.99999999,尽管从逻辑上讲您会期望恰好是 1。所以你的条件可能永远不会是假的!

通常你宁愿给它一个特定的范围,例如

while(Mathf.Abs(Blendfloat - 1) > certainThreshold)

Unity 有 Mathf.Approximately

while(!Mathf.Approximately(Blendfloat, 1f)

这基本上等于与 Mathf.Epsilon

的阈值进行比较
which(Math.Abs(Blendfloat - 1) > Mathf.Epsilon)

请注意,无论如何你现在拥有的将在 一个单帧 .

中执行整个循环

如果你真的想让它随着时间的推移而淡出,你需要每帧进行一次迭代,例如协程!