c# - 如何在 C# 中等待 3 秒然后将 bool 设置为 true?

标签 c# timer unity3d

我的脚本/游戏/东西让一个游戏对象向右移动,当我点击跳舞(我创建的一个按钮)时它停止了。然后当计数器(我可能不需要计数器,但我想等 3 秒)达到 3(一旦你点击跳舞,计数器开始)我的游戏对象应该继续向右移动。

如果您可以更正代码,那就太好了。 如果你能纠正它并向我解释我做错了什么,那就更棒了。我刚开始在 Unity 上学习 C#。

using System;
using UnityEngine;
using System.Collections;

public class HeroMouvement : MonoBehaviour
{
    public bool trigger = true;
    public int counter = 0;
    public bool timer = false;

    // Use this for initialization

    void Start()
    {
    }

    // Update is called once per frame

    void Update()
    {  //timer becomes true so i can inc the counter

        if (timer == true)
        {
            counter++;
        }

        if (counter >= 3)
        {
            MoveHero();//goes to the function moveHero
        }

        if (trigger == true)
            transform.Translate(Vector3.right * Time.deltaTime); //This moves the GameObject to the right
    }

    //The button you click to dance 
    void OnGUI()
    {
        if (GUI.Button(new Rect(10, 10, 50, 50), "Dance"))
        {
            trigger = false;
            timer = true;//now that the timer is set a true once you click it,The uptade should see that its true and start the counter then the counter once it reaches 3 it goes to the MoveHero function      
        }
    }

    void MoveHero()
    {  //Set the trigger at true so the gameobject can move to the right,the timer is at false and then the counter is reseted at 0.
        trigger = true;
        timer = false;
        counter = 0;
    }
}

最佳答案

你可以用协程很容易地做到这一点:

void Update()
{
    if (trigger == true)
        transform.Translate(Vector3.right * Time.deltaTime); //This moves the GameObject to the right
}

void OnGUI()
    {
        if (GUI.Button(new Rect(10, 10, 50, 50), "Dance"))
        {  
           StartCoroutine(DoTheDance());
        }
    }


 public IEnumerator DoTheDance() {
    trigger = false;
    yield return new WaitForSeconds(3f); // waits 3 seconds
    trigger = true; // will make the update method pick up 
 }

参见 https://docs.unity3d.com/Manual/Coroutines.html有关协程及其使用方法的更多信息。在尝试进行一系列定时事件时,它们非常简洁。

关于c# - 如何在 C# 中等待 3 秒然后将 bool 设置为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16929805/

相关文章:

python - 限时输入?

c# - 将计时器值存储在数据库中? C#

c# - 如何在指定的随机间隔内生成敌人?

unity3d - 无法登录 Unity : Sorry, 此链接不再有效

c# - 如何将 JNI C# 类传递给 Java 或处理这种情况?

c# - 以编程方式为多个字节上的相关位创建位掩码

c# - Xamarin:构建时出错 -> 无效的文件路径 'obj\Debug\90\res\views\layouttest.xml'

c# - 触发内容模板

c# - 如何在 C# 中将小时从 h 转换为 hh

tableView 单元格内的快速计时器失效