使用协程计算对象

Counting objects with Coroutine

在我的项目中,我试图计算不同的对象并模拟一个小动画,例如我的游戏中有星星,我想计算游戏决赛中星星的数量从 0 到数字用户获得的星星数,所以我这样做了:

public void youWin()
    {
        audio.Stop ();
        StartCoroutine (activatePanel ());
    }

    IEnumerator activatePanel()
    {
        yield return new WaitForSeconds (3f);
        pausePanel2.SetActive (true);
        for (int i = 0; i <= stars; i++) {
            yield return new WaitForSeconds (0.2f);
            starText2.text = i + "";
        }
    }

我的代码在 for 循环等待几秒钟时对于 0.3f 运行良好,但它太慢了,我想要它用于 0.2f,但有时会发生一些奇怪的事情,它就像一个错误,第一个数字似乎消失了回来了,算错了,有人知道怎么回事吗?

很可能 activatePanel 函数在它已经 运行 时从另一个地方调用,或者包含此代码的脚本附加到多个游戏对象和 activatePanel再次被另一个函数调用。您可以使用标志来阻止这种情况的发生。

如果协程函数已经是运行,使用yield break;跳出

bool isRunning = false;
IEnumerator activatePanel()
{
    //Exit if already running
    if (isRunning)
    {
        yield break;
    }

    //Not running, now set isRunning to true then run
    isRunning = true;

    yield return new WaitForSeconds(3f);
    pausePanel2.SetActive(true);

    WaitForSeconds waitTime = new WaitForSeconds(0.2f);
    for (int i = 0; i <= stars; i++)
    {
        yield return waitTime;
        starText2.text = i.ToString();
    }

    //Done running, set isRunning to false
    isRunning = false;
}

好吧,我在你们所有人的帮助下解决了它,实际上你们都对,我以为我只调用了 1 次 youWin 函数,但我忘记了这是统一的,我在 trigerEnter 函数中调用了 youWin,这意味着对象不断进入triger函数并调用youWin函数,谢谢大家这里就是我的意思

用输入的布尔值解决了

public class Victory : MonoBehaviour {

Manager gameManager;
// Use this for initialization
public AudioClip clip;
private AudioSource audio;
public Animator girl;
private bool entered;


void OnTriggerEnter(Collider c)
{
    if (c.gameObject.tag == "Player" && !entered) {
        gameManager.win = true;
        audio.clip = clip;
        audio.Play ();
        gameManager.Ball.GetComponent<MoveBall> ().enabled = true;
        girl.SetBool ("win",true);
        entered = true;
        gameManager.youWin ();
    }
}

void Start () {
    gameManager = GameObject.Find ("GameController").GetComponent<Manager> ();
    audio = GetComponent<AudioSource> ();
    entered = false;

}

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

}
}