3

我需要每 x 秒执行一次代码,直到在 Unity3D C# 中满足条件。只要条件为真,代码就应该运行而与其他代码无关,否则停止。一旦条件变为假,它应该停止执行并在条件变为真时再次运行(如果可能,再次从 0 开始计数秒数)。怎么做?

4

3 回答 3

6

实际上,有比使用带有 yield 的协程更好的方法。InvokeRepeating方法的开销更少,并且不需要丑陋的 while(true) 构造:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
    public Rigidbody projectile;
    public bool Condition;
    void LaunchProjectile() {
        if (!Condition) return;
        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5;
    }
    void Start() {
        InvokeRepeating("LaunchProjectile", 2, 0.3F);
    }
}

另外,您的病情是如何定义的?如果它是一个属性会更好——这样你就不必每次都检查它:

public class Example : MonoBehaviour {
    public Rigidbody projectile;
    private bool _condition;
    public bool Condition {
        get { return _condition; }
        set
        {
            if (_condition == value) return;
            _condition = value;
           if (value)
               InvokeRepeating("LaunchProjectile", 2, 0.3F);
           else
                CancelInvoke("LaunchProjectile");
    }
    void LaunchProjectile() {
        Rigidbody instance = Instantiate(projectile);
        instance.velocity = Random.insideUnitSphere * 5;
    }
}
于 2013-08-13T07:41:30.393 回答
5

像这样的东西应该工作。

void Start(){
    StartCoroutine("DoStuff", 2.0F);
}

IEnumerator DoStuff(float waitTime) {
    while(true){
        //...do stuff here
        if(someStopFlag==true)yield break;
        else yield return new WaitForSeconds(waitTime);
    }
}
于 2013-08-12T19:46:18.743 回答
0

MonoBehaviour.InvokeRepeating

描述在 time 秒内调用方法 methodName,然后每隔 repeatRate 秒重复一次。

注意:如果您将时间刻度设置为 0,这将不起作用。

using UnityEngine;
using System.Collections.Generic;

// Starting in 2 seconds.
// a projectile will be launched every 0.3 seconds

public class ExampleScript : MonoBehaviour
{
    public Rigidbody projectile;

    void Start()
    {
        InvokeRepeating("LaunchProjectile", 2.0f, 0.3f);
    }

    void LaunchProjectile()
    {
        Rigidbody instance = Instantiate(projectile);

        instance.velocity = Random.insideUnitSphere * 5;
    }
}
于 2018-09-12T08:23:52.573 回答