简体   繁体   English

如何延迟启动 x 秒?

[英]How to delay start for x seconds?

I've searched around and couldn't quite find the answer.我四处搜索,并没有完全找到答案。 I have two scenes, one with a play button which starts the next scene (the game) and the other scene is the game.我有两个场景,一个带有开始下一个场景(游戏)的播放按钮,另一个场景是游戏。 Which has a spawner script which spawns random patterns of obsticles.它有一个 spawner 脚本,可以生成随机模式的障碍物。 Which can be seen here.可以在这里看到。

public class Spawner : MonoBehaviour {
public GameObject[] obstaclePatterns;

private float timeBtwSpawn;
public float startTimeBtwSpawn;
public float decreaseTime;
public float minTime = 0.55f;

private void Update()
{
    if (timeBtwSpawn <= 0)
    {
        int rand = Random.Range(0, obstaclePatterns.Length);    
        Instantiate(obstaclePatterns[rand], transform.position, Quaternion.identity);
        timeBtwSpawn = startTimeBtwSpawn;
        if (startTimeBtwSpawn > minTime) {
            startTimeBtwSpawn -= decreaseTime;
        }

    }
    else {
        timeBtwSpawn -= Time.deltaTime;
    }
}}

I would like to after the play button is pressed and the game is started there be a delay for 1 second before the spawner begins spawning.我想在按下播放按钮并开始游戏后,在生成器开始生成之前有 1 秒的延迟。 I'm not sure how to do that.我不知道该怎么做。 Any help would be appreciated.任何帮助,将不胜感激。

You can use Unity's Start function as a coroutine directly.你可以直接使用Unity的Start函数作为协程。


private bool _canStart;

private IEnumerator Start()
{
    yield return new WaitForSeconds(whatyouwant);
    _canStart = true;
}

private void Update()
{
    if(!_canStart) return;

    whatyouwant
}

如果你想有一个例程在加载场景后的特定时间后启动,你可以使用Time.timeSinceLevelLoad 这个变量保存自上一个关卡(场景)加载以来的时间(以秒为单位)所以你可以创建一个脚本激活您的 spawner 脚本或向您的 spawner 脚本添加额外的检查

您应该在开始更新 Spawner 之前设置 timeBtwSpawn:

timeBtwSpawn = 1; // seconds

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM