- Home /
Same script on multiple objects.
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;
}
}
}
Ins$$anonymous$$d of destroying objects, simply disable them and re-enable them later. It will do good to your performance. Look at object pooling.
Answer by TwinGhosts · Aug 11, 2017 at 05:23 PM
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
}
}
Answer by KrKOo · Aug 11, 2017 at 02:52 PM
OK, now i have this script, but when I "destroy" more objects at the same time, only the last one will respawn. Any ideas what should I do ?
float spawnTime = 5;
float time = 0;
bool timer = false;
GameObject Item;
void Start ()
{
}
void Update()
{
if (timer == true)
{
time += Time.deltaTime;
if (time >= spawnTime)
{
Item.SetActive(true);
timer = false;
time = 0;
}
}
}
public void setSpawned(GameObject obj, bool spawned)
{
Item = obj;
obj.SetActive(spawned);
timer = true;
}
Your answer
