如何等待3秒钟,然后在C#中设置一个bool为true?

前端之家收集整理的这篇文章主要介绍了如何等待3秒钟,然后在C#中设置一个bool为true?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的脚本/游戏/东西让一个gameobject向右移动,当我点击舞蹈(我创建的一个按钮)它停止.然后当柜台(我可能不需要一个柜台,但我想等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,"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 
 }

有关Coroutines的更多信息以及如何使用它们,请参阅http://docs.unity3d.com/Documentation/ScriptReference/index.Coroutines_26_Yield.html.当他们试图做一个定时的一系列的事件时,他们很整齐.

原文链接:/csharp/94446.html

猜你在找的C#相关文章