So I downloaded this script for spawning objects. It works really well but there is a problem: the objects that get spawned never gets removed, which creates lots of lag. Of course I understand that they wouldn’t randomly get removed without me programming a single code but i don’t really know how I am supposed to use the Destroy function to do what i want. Here is the script:
var prefabToSpawn:Transform;
var spawnTime:float;
var spawnTimeRandom:float;
private var spawnTimer:float;
function Awake()
{
ResetSpawnTimer();
}
function Update()
{
if(spawnTimer > 0)
{
spawnTimer -= Time.deltaTime;
if(spawnTimer <= 0.0)
{
spawnTimer = 0;
Instantiate(prefabToSpawn, transform.position, Quaternion.identity);
ResetSpawnTimer();
}
}
}
function ResetSpawnTimer()
{
spawnTimer = spawnTime + Random.Range(0, spawnTimeRandom*100)/100.0;
}
The Destroy function can take a parameter saying how long it will be before the object is destroyed. Also that script would be made a lot simpler by using a coroutine.
var minSpawnTime = 1.0;
var maxSpawnTime = 10.0;
var prefabToSpawn : GameObject;
var prefabLifetime = 3.0;
function Start () {
while (true) {
yield WaitForSeconds (Random.Range (minSpawnTime, maxSpawnTime));
Destroy (Instantiate (prefabToSpawn, transform.position, Quaternion.identity),
prefabLifetime);
}
}
You can call Destroy() with a future time parameter, so you can call Destroy() on your just created game object:
var go : GameObject = Instantiate(prefabToSpawn, transform.position, Quaternion.identity);
Destroy(go, 3.0);
Create a script that has this in it, then attach this script to the prefab you are instantiating:
private var Spawntime : float;
public var TimeInSecondsTillDestroyed : float;
function Awake(){
SpawnTime = Time.time + TimeInSecondsTillDestroyed;
}
function Update(){
if(Spawntime < Time.time){
Destroy(this.GameObject);
}
}
Once added, in the inspector, put the amount of time you want to wait till it destroys itself.