Can somebody please explain WaitForSeconds()?

折月煮酒 提交于 2021-01-28 15:26:44

问题


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;
}

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?


回答1:


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;
}

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.



来源:https://stackoverflow.com/questions/38807458/can-somebody-please-explain-waitforseconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!