Hi!
I’m trying to make a game where objects will respawn in 5 seconds after it was destroyed.
I have this script attached on empty gameobjects on which the objects are spawning. The problem is, that it is not working when i have more of these empty gameobjects. Can someone help me please ??
public GameObject Item;
float spawnTime = 5;
float time = 0;
public bool spawned;
void Start ()
{
Instantiate(Item, gameObject.transform.position, Quaternion.identity);
spawned = true;
}
void Update()
{
if (spawned == false)
{
time += Time.deltaTime;
if (time >= spawnTime)
{
Instantiate(Item, gameObject.transform.position, Quaternion.identity);
time = 0;
spawned = true;
}
}
}
Don’t destroy them, you could use something like object-pooling to get more control over the objects. But aside from that, if you have a set amount of Object you could make them inactive outside of the screen and reactivate them again when they respawn.
I’ve made some test code for you to experiment with - it should work when you put this on your GameObject that has to respawn. You just need to write code which can make it die though.
using UnityEngine;
public class Dissapear : MonoBehaviour {
float respawnTime = 5f;
Vector3 respawnPosition;
bool isAlive = true;
// Update is called once per frame
void Update () {
// Check whether the object is alive or not and when it is not try to respawn it
if (!isAlive) {
// If it isnt trying to respawn yet, make it respawn
if (!IsInvoking ("Respawn")) {
Invoke ("Respawn", respawnTime); // Respawn the object after 5 sec
}
// Deactivate the object because it is not active
transform.position = new Vector3(-1000f, -1000f, transform.position.z);
} else {
//TODO actions when it is active
// Set the respawnPosition for as long as it is alive
respawnPosition = transform.position;
// You can call this once when it dies, but itś just to show you how it can be done.
}
}
void Respawn(){
isAlive = true; // Set the object back to alive so that it can die again
transform.position = respawnPosition; // Set it back to its original position when it died
}
}