- Home /
Delay spawning Objects in MainLevel
Hello,
I have a script for Coins Spawn. Everything works fine until player dies and he resets the scene. After reseting the scene the coins are spawning instantly and there is no delay. The script is the following:
using UnityEngine;
public class ObjectPooler : MonoBehaviour
{
public Transform[] spawnCoins;
public GameObject coinPrefab;
public float timeBetweenWavesC = 15f;
private float timeToSpawnC = 5f;
void Update()
{
if (Time.time >= timeToSpawnC)
{
SpawnCoins();
timeToSpawnC = Time.time + timeBetweenWavesC;
}
}
void SpawnCoins()
{
int randomIndex = Random.Range(0, spawnCoins.Length);
for (int i = 0; i < spawnCoins.Length; i++)
{
if (randomIndex != i)
{
Instantiate(coinPrefab, spawnCoins[i].position, Quaternion.identity);
}
}
}
}
I want the coins to spawn at the time indicated in the script even if the player resets the scene. Any ideas? Thank you?
Answer by EDevJogos · Nov 20, 2017 at 07:09 PM
Time.time is time since the game started:
So when you Load the scene again your timeToSpawnC
will have the value 5, but Time.time will be the time since the game started, probably higher than 5.
What you can do is on the method Start()
say that timeToSpawnC = Time.time + 5;
this way when you reload the scene it'll take 5 seconds for the coins to spawn.
Answer by ZeN12 · Nov 21, 2017 at 08:36 AM
You can set variable "timeToSpawnC" to be static, like this:
private static float timeToSpawnC = 5f;
In this case, the value of timeToSpawnC won't change after restarting level.