Spawn item after n seconds?

Hi guys,
I’m having trouble getting items to respawn when it isn’t right away (3 seconds later instead). I’ve done one where the item is on a timer then gets reinstantiated instantly but can’t get this method to work haven’t found any examples online that I could get to work (http://answers.unity3d.com/questions/7521/how-to-respawn-a-game-object-after-a-certain-amount-of-time)

 // ItemCollection.js
function OnTriggerEnter (hit : Collider) 
{
	var respawnTime:int = 3;
	// send message to spawn new item with location  wait time	
	GetComponent("Spawning").SpawnItem(gameObject.transform.position, respawnTime);	
	// destroy this item
	Destroy(gameObject);
}
 // Spawning.js
var item:GameObject;
private var pos : Vector3;

// Function runs at start
function Start()
{
}

// Function to SpawnItem 
function SpawnItem(position : Vector3, delayTime : int)
{	
   pos = position;	      
   yield WaitForSeconds(delayTime);
   var newObject = Instantiate(item, pos,Quaternion.identity);
}

Both of these scripts are attached to prefabs (different valued armours) and the GameObject in the second script is also the prefab (prefab red contains a script which references itself – red)…is this not a good/correct way to relate them?

The armours get drestroyed but then never respawn.

Here is an image of the hierarchy/project/inspector: ImageShack - Best place for all of your image hosting and image sharing needs

Thanks for any help.

Once the instances are destroyed, their scripts won’t continue to run, so it’s never going to spawn a new object (the script to do so has been destroyed).

I’d recommend having these objects send a message to a different object (one that isn’t destroyed), and have it handle all of the item respawning. Just make an empty object called “itemSpawner” and attach code to create new objects whenever its told. Then the armor can send out the signal to itemSpawner, then be destroyed, trusting that the itemSpawner will do its job after they’re gone.

While I’m here, I could also recommend that you look into the Invoke and Instantiate methods. Very, very handy for stuff like this.

Hi Khan,

I’ve done it now except I’ve used object.active = false instead of destroy. Thanks though.

in this way you are using always the same object… I would suggest you to keep the destroy command and to cancel the WaitForSeconds one. Try to use InvokeRepeating to call at regular intervals the spawn function :slight_smile:

Ops didn’t see reply from Khan…

I think this is the best way of doing it, just pass the location you want the object to spawn at, then the time in seconds you want it to wait.
Just make sure you call StartCoroutine if your using the yield new WaitForSeconds(1);