我的剧本/游戏/东西让游戏对象向右移动,当我点击舞蹈(我创建的按钮)时,它会停止。然后,当计数器(我可能不需要计数器,但我想等待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;
}
}
答案 0 :(得分:15)
你可以使用协同程序轻松完成:
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。在尝试进行一系列定时活动时,它们非常整洁。
答案 1 :(得分:9)
答案 2 :(得分: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
}
答案 3 :(得分:3)
首先使计数器浮动。
然后将counter++;
更改为counter += Time.deltaTime
。
每个帧都调用Update(),因此第三帧的计数器将为3。 Time.deltaTime为您提供此帧与前一帧之间的时间。总结它就像一个计时器。
答案 4 :(得分:-3)
如果是多线程,我会使用它:
DateTime a = DateTime.Now;
DateTime b = DateTime.Now.AddSeconds(2);
while (a < b)
{
a = DateTime.Now;
}
bool = x;
答案 5 :(得分:-8)
如果只需要等待,可以使用Thread的sleep方法
System.Threading.Thread.Sleep(3000);