有人可以解释一下 WaitForSeconds() 吗? [英] Can somebody please explain WaitForSeconds()?
问题描述
我试图让我的代码在做某事之前等待 x
秒.我查找了如何执行此操作,并发现了 WaitForSeconds()
函数.不幸的是,每当我尝试使用它时,我的代码中都会出现红色下划线.我试图让它在你死后等待几秒钟后再重生:
I am trying to make my code wait x
seconds before doing something. I looked up how to do this, and found out about the WaitForSeconds()
function. Unfortunately, whenever I try to use it I get red underlines in my code. I am trying to make it so when you die it waits a few seconds before you respawn:
void Respawn()
{
yield return new WaitForSeconds(5);
gameObject.transform.position = spawnPoint;
}
我也明白我需要在某处放置诸如 StartCoroutine(Example());
之类的东西,但我也不知道把它放在哪里.我该如何正确执行此操作?
I also understand I need to put something like StartCoroutine(Example());
somewhere but I also don't know where to put it. How do I do this properly?
推荐答案
yield return new WaitForSeconds(5);
必须在协程函数中使用.现在,您在 void
函数 void Respawn()
中使用它.将 void
更改为 IEnumerator
应该可以解决您的问题.
yield return new WaitForSeconds(5);
must be used in a coroutine function. Right now, you are using it in a void
function void Respawn()
. Changing the void
to IEnumerator
should fix your problem.
IEnumerator Respawn()
{
yield return new WaitForSeconds(5);
gameObject.transform.position = spawnPoint;
}
然后你可以用StartCoroutine(Respawn());
调用它.每次调用它都会等待5
秒,然后执行gameObject.transform.position = spawnPoint;
.如果您想了解其工作原理,请访问此处.
Then you can call it with StartCoroutine(Respawn());
. Each time you call it, it will wait for 5
seconds, then execute gameObject.transform.position = spawnPoint;
. Visit here if you want to learn how it works.
这篇关于有人可以解释一下 WaitForSeconds() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!