- Home /
how to delay spawnrate
so im having trouble with this but its propably easy to solve, the thing is im learning and dont know how to make lots of things. so, i have a script that spawns objects every 3 seconds on the right of the screen. but i also have another script for objects to spawn on the left. the problem is that these two objects spawn at the same time and i want them to keep the same rate. so i thinked of making a delay of 1 or 2 seconds for the first object to spawn on the right for example, this way the objects on the right and in the left have the same rate but spawn at different times because of that first delay. but i dont know how to do it in code terms. this is the script for the objects on the right:
public class Spawnaster : MonoBehaviour
{
public GameObject asteroidprefab;
public float respawntime = 3.0f;
private Vector2 screenBounds;
// Start is called before the first frame update
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.height, Camera.main.transform.position.z));
StartCoroutine(asterspawnrate());
}
private void spawnenemy()
{
GameObject a = Instantiate(asteroidprefab) as GameObject;
a.transform.position = new Vector2(screenBounds.x * -2, Random.Range(-screenBounds.y, screenBounds.y));
}
IEnumerator asterspawnrate()
{
while (true)
{
yield return new WaitForSeconds(respawntime);
spawnenemy();
}
}
}
if it is kind bullet fire or you need to do it continusly then you can try like
float nextSpawnTime;
float delay = 0.5f;
void Update(){
if(time.Time > nextSpawnTime){
SpawnTime = time.Time+delay;
// spawn enemy
}
}
Answer by Hellium · Aug 22, 2019 at 05:12 AM
public float respawntime = 3.0f;
public float firstSpawnDelayOffset = 1.5f;
IEnumerator asterspawnrate()
{
yield return new WaitForSeconds(respawntime + firstSpawnDelayOffset);
while (true)
{
spawnenemy();
yield return new WaitForSeconds(respawntime);
}
}
Answer by galalhassan · Aug 22, 2019 at 03:38 AM
Dont use coroutines, use invoke instead. Check this link: https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
Your answer
Follow this Question
Related Questions
Delaying in for loop, Spawning enemies 1 Answer
delay first spawn 2 Answers
How do I put a delay in this script ? 1 Answer
Classic Fireball Shooting Up Obstacle 1 Answer
Adding Delay to a for loop in C# 1 Answer