I have created a Spawner script to spawn in selected blocks and I would like to enable and disable this spawning after a set amount of time.
Here are my two scripts so far, both c#.
Spawner.cs:
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax= 2f;
// Use this for initialization
void Start () {
Spawn ();
}
void Spawn () {
Instantiate(obj[Random.Range (0, obj.GetLength(0))], transform.position, Quaternion.identity);
Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
}
}
DeleyScript.cs:
using UnityEngine;
using System.Collections;
public class DelayScript : MonoBehaviour {
public float delay;
public float endtime;
float startTime = 0.0f;
private Spawner spawn;
//public string comp = "Spawner";
void Awake (){
startTime = Time.time;
}
void Start ()
{
spawn = GetComponent<Spawner>();
spawn.enabled = false;
}
void Update (){
if ((Time.time - startTime) >= delay)
{
if ((Time.time - startTime) >= endtime)
{
spawn.enabled = false;
}
else{
spawn.enabled = true;
}
}
}
}
Both these scripts work and the component is turned on and off in the inspector BUT, after it has been disabled it continues to spawn objects.
I have read somewhere that this is because the code ‘spawn.enabled = false;’ only stops the Update function.
Is this correct and if so, what can I do to stop my entire script and stop all the spawning.
Instead of using Invoke() in you Spawn script, have an update loop with a simple delay mecanic like for the enabling script. This way the enabling/disabling will work as it should since the update will stop being called after your script is disabled, which is FYI, unity stuff as oppposite to invoke which is mono stuff and doesn’t give a damn of unity’s disabling ^^.
Thanks for the help,
I tried to put the spawn function into a while loop but that crashed my game and editor, no error message, just froze when i tried to play.
You have also recommended i get rid of the Invoke and put that into an Update. How would you recommend i do that without it re-spawning objects every frame. Sorry, i’m pretty new to this.
Any help is appreciated, thank you.
While is a loop. And if there’s nothing inside the loop that could turn the while condition to false, you’ve created an infinite loop so you crash. The only time you can get away with that is if it’s a coroutine with a yield call, because the yield call will allow things to progress outside the coroutine.
_met44’s got another idea that could work. You’ve got something comparing delay to start time to decide when you do something. You could give your spawner its own delay variable, and then increase it by a random amount each time you reach it.