Fro*_*oob 16 c# timer unity-game-engine
我的脚本/游戏/东西使游戏对象向右移动,当我点击舞蹈(我创建的按钮)时,它停止.然后当计数器(我可能不需要计数器,但我想要等待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;
}
}
Run Code Online (Sandbox Code Playgroud)
Jan*_*omä 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
}
Run Code Online (Sandbox Code Playgroud)
有关Coroutines以及如何使用它们的更多信息,请参见http://docs.unity3d.com/Documentation/ScriptReference/index.Coroutines_26_Yield.html.在尝试进行一系列定时活动时,它们非常整洁.
小智 10
我认为最简单的方法是使用Invoke:
if (timer == true) Invoke("MoveHero", 3);Run Code Online (Sandbox Code Playgroud)
小智 3
首先让计数器成为一个浮动。然后更改counter++;为counter += Time.deltaTime. 每帧都会调用 Update(),因此第三帧上的计数器将为 3。Time.deltaTime 为您提供此帧与上一帧之间的时间。总结起来就像一个计时器。