我怎么能等待3秒,然后设置一个bool为真,在c#

本文关键字:bool 一个 为真 等待 怎么能 3秒 然后 设置 | 更新日期: 2023-09-27 18:17:01

我的脚本/游戏/东西使游戏对象向右移动,当我点击舞蹈(我创建的按钮)时它停止。然后,当计数器(我可能不需要计数器,但我想等待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;
    }
}

我怎么能等待3秒,然后设置一个bool为真,在c#

使用协程很容易做到这一点:

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了解有关协程及其使用方法的更多信息。当尝试执行一系列定时事件时,它们非常简洁。

我认为最简单的方法是使用Invoke:

Unity3D调用

if (timer == true) Invoke("MoveHero", 3);

我更喜欢使用StartCoroutine链接如下:http://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

,

   void Foo () { StartCoroutine (Begin ()); }
   IEnumerator Begin ()
    {
        yield return new WaitForSeconds (3);
         // Code here will be executed after 3 secs
        //Do stuff here
    }

首先将counter设置为float。将"counter++;"改为"counter += Time.deltaTime"。每帧调用Update(),因此第三帧的counter将为3。time。deltatime给出了这一帧和前一帧之间的时间。总结就像一个计时器。

我将在多线程中使用这个:

    DateTime a = DateTime.Now;
    DateTime b = DateTime.Now.AddSeconds(2);
    while (a < b)
    {
        a = DateTime.Now;
    }
    bool = x;

如果你只需要等待,你可以使用Thread的sleep方法

System.Threading.Thread.Sleep(3000);
相关文章: