我的脚本/游戏/事物使游戏对象向右移动,当我单击舞动(我创建的按钮)时,它停止了。然后,当计数器(我可能不需要计数器,但我想等待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。尝试进行定时的一系列事件时,它们非常简洁。