c# - 使用切换按钮停止协程

标签 c# unity3d

我有一个协程,当切换按钮的 bool 值发生变化时触发,当 bool 值再次改变时,协程应该停止,另一个应该开始。这是我的代码:

    public class thermoPowerControlPanel : MonoBehaviour {

    private ThermoElectric thermo;

    public bool toggleBool1;
    public int temperature;
    private int tempUp = 10;
    private int tempDown = 1;


    public thermoPowerControlPanel (){
        temperature = 100;
    }


    public void turbine1State (bool toggleBool1) {

        if (toggleBool1 == false) {
            Debug.Log (toggleBool1);
            Invoke("ReduceTemperatureEverySecond", 1f);
        }

        if (toggleBool1 == true) {
            Debug.Log (toggleBool1);
            Invoke("IncreaseTemperatureEverySecond", 1f);
        }
    }


    private void ReduceTemperatureEverySecond()
    {
        if (toggleBool1 == true)
        {
            Debug.Log("I was told to stop reducing the temperature.");
            return;
        }
        temperature = temperature - tempDown;
        Debug.Log (temperature);
            Invoke("ReduceTemperatureEverySecond", 1f);
    }

    private void IncreaseTemperatureEverySecond()
    {
        if (toggleBool1 == false)
        {
            Debug.Log("I was told to stop increasing the temperature.");
            return;
        }
        temperature = temperature + tempUp;
        Debug.Log (temperature);
        Invoke("ReduceTemperatureEverySecond", 1f);
    }
}

当函数 turbine1State(bool t1) 接收到第一个 bool (false) 时,例程 decreaseTemperatureEverySecond() 开始但在发送 Debug.Log 消息后立即停止,它应该继续降低温度直到 bool(由切换按钮)变为真。 .

你能帮忙吗?

最佳答案

就这么简单!

 public Toggle tog;  // DONT FORGET TO SET IN EDITOR

开始 ...

 InvokeRepeating( "Temp", 1f, 1f );

...然后...

private void Temp()
 {
 if (tog.isOn)
     temperature = temperature + 1;
 else
     temperature = temperature - 1;
 
 // also, ensure it is never outside of 0-100
 temperature = Mathf.Clamp(temperature, 0,100);
 }

如果你需要“完全停止”那个 Action (上下),就这样做

 CancelInvoke("Temp");

很简单!


注意仅供引用,我解释的另一种模式是这样的:

 bool some flag;
 Invoke("Temp", 1f);
 private void Temp()
   {
   if (some flag is tripped) stop doing this
   .. do something ..
   Invoke( ..myself again after a second .. )
   }

在现实生活中,“不断调用自己”通常比使用 InvokeRepeating 更好。

在这个简单的示例中,只需使用 InvokeRepeating,然后使用 CancelInvoke。

关于c# - 使用切换按钮停止协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36013265/

相关文章:

c# - 在 c# 中使用 [] 接口(interface)(不是来自 ILIst)构建对象

c# - 是否可以编写会导致编译时间过长的代码?

c# - Unity SetActive(true) 一开始设置为 false 后不工作?

c# - Request.Url.Port 给出了错误的端口

c# - 使用 'do nothing' 默认事件处理程序是否存在任何性能缺陷?

c# - C#await运算符的理解

c# - 如何为图形或树结构编写 GUI 编辑器

c# - 我如何检测用户何时单击我的 slider 而不是统一滑动?

java - 用于 C# .Net 框架的 AndroidJavaClass 和 AndroidJavaObject

c# - 每个 “foreach” 循环的每次迭代都会生成 24 字节的垃圾内存?