简体   繁体   中英

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. 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. I'm not sure how to do that. Any help would be appreciated.

You can use Unity's Start function as a coroutine directly.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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