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