我想让代码在之类的if语句中运行几秒钟 每当我按“ e”时,使BoxCollider.enabled = false,几秒钟后再次使BoxCollider.enabled = true。。我该怎么办?
我尝试了invoke方法,但是它不起作用。
if (Input.GetKeyDown("e"))
{
BoxCollider.enabled = false;
Invoke("enable", 2f);
}
void enable()
{
BoxCollider.enabled = true;
}
答案 0 :(得分:1)
好吧,我和您一样都是新手,但我想我有解决您问题的方法
public float waitTime = 0f;
public void Update()
{
waitTime = waitTime + Time.deltaTime;
if (Input.GetKeyDown("e"))
{
BoxCollider.enabled = false;
waitTime = 0;
}
if (waitTime >= 2)
{
BoxCollider.enabled = true;
}
}
我在这里所做的是我创建了一个计数秒的变量,并在用户按下E之后将其重置为0,然后当它变为2时,boxCollider.enabeled = true再次
答案 1 :(得分:1)
最优雅的方式是使用协程
if (Input.GetKeyDown("e")){
BoxCollider.enabled = false;
StartCoroutine(EnableCoroutine());
}
...
IEnumerator EnableCoroutine() {
//A coroutine can 'wait' until something is done
//yield return null; would wait a single frame
yield return new WaitForSeconds(2);
//After 2 seconds the following code will be executed
BoxCollider.enabled = true;
}
答案 2 :(得分:0)
您可以使用计时器。
尝试以下示例:
class Program
{
static bool boxCollider = true;
static Timer aTimer;
static void Main(string[] args)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.E)
{
Console.WriteLine("The key was pressed at {0:HH:mm:ss.fff}", DateTime.Now);
boxCollider = true;
aTimer = new System.Timers.Timer(2000);
aTimer.Elapsed += onTimerEnded;
aTimer.Enabled = true;
}
Console.ReadLine();
}
private static void onTimerEnded(object sender, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
Enable();
aTimer.Enabled = false;
aTimer.Dispose();
}
private static void Enable()
{
boxCollider = true;
}
达到间隔时间后,BoxCollider将被重置。