Как я могу подождать 3 секунды, а затем установить bool в true, в С#?
My script/game/thing делает игру с движением вправо, и когда я нажимаю танец (кнопка, которую я создал), она останавливается. Затем, когда счетчик (мне может не понадобиться счетчик, но я хочу подождать 3 секунды), достигнет 3 (как только вы нажмете на танец, который запускает счетчик) мой игровой объект, предположим, продолжит движение вправо.
Если вы можете исправить код, который будет круто.
Если вы можете исправить это и объяснить мне, что я сделал не так, это было бы еще более удивительным. Я только начал изучать С# на Unity.
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;
}
}
Ответы
Ответ 1
Вы можете сделать это довольно легко с сопрограммами:
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
}
Подробнее о Coroutines и о том, как их использовать, см. http://docs.unity3d.com/Documentation/ScriptReference/index.Coroutines_26_Yield.html. Они очень аккуратны при попытке выполнить запланированную последовательность событий.
Ответ 2
Я думаю, что самый простой способ - использовать Invoke:
Unity3D Invoke
if (timer == true) Invoke("MoveHero", 3);
Ответ 3
Сначала сделайте счетчик поплавком.
Затем измените counter++;
на counter += Time.deltaTime
.
Для каждого кадра вызывается Update(), поэтому счетчик будет равен 3 на третьем кадре. Time.deltaTime дает вам время между этим кадром и предыдущим кадром. Подведение итогов действует как таймер.
Ответ 4
Я предпочитаю использовать 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
}
Ответ 5
System.Threading.Thread.Sleep
Thread.Sleep(3000) // In miliseconds.
timer = true;
Ответ 6
Я бы использовал это, если многопоточность:
DateTime a = DateTime.Now;
DateTime b = DateTime.Now.AddSeconds(2);
while (a < b)
{
a = DateTime.Now;
}
bool = x;
Ответ 7
если вам нужно только подождать, вы можете использовать метод сна Thread
System.Threading.Thread.Sleep(3000);