- Home /
How to Spawn after checking if the clones are destroyed.
I want to spawn some gameobjects which on destroyed should be spawned again.
I currently have this piece of code:
public static bool IsDestroyed(this GameObject gameObject)
{
// UnityEngine overloads the == opeator for the GameObject type
// and returns null when the object has been destroyed, but
// actually the object is still there but has not been cleaned up yet
// if we test both we can determine if the object has been destroyed.
return gameObject == null && !ReferenceEquals(gameObject, null);
}
But this doesnt seem to work.
Thanks in Advance!
Answer by RodrigoAbreu · Feb 12, 2021 at 04:50 AM
@Manhiem what you need is an object pool, and when the object is destroyed, it would merely put itself back to it's pool to be available to respawn again if needed.
Something like this, or adapt to what you need. PS.: I didn't test this, just wrote down the idea here:
public class ObjectPool : MonoBehaviour
{
public static ObjectPool Instance { get; private set; }
[SerializeField] private int capacity;
[SerializeField] private GameObject objectPrefab;
private Stack<GameObject> pool = new Stack<GameObject>();
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
DontDestroyOnLoad(gameObject);
Initialize();
}
private void Initialize()
{
if (capacity > 0)
{
for (int i = 0; i < capacity; i++)
{
GameObject obj = Instantiate(objectPrefab, Vector3.zero, Quaternion.identity, transform);
obj.SetActive(false);
pool.Push(obj);
}
}
}
public GameObject GetObject(Vector3 position)
{
if (pool != null)
{
if (pool.Count <= 0)
{
Initialize();
}
var obj = pool.Pop();
obj.transform.position = position;
return obj;
}
return null;
}
public void ReturnObject(GameObject gameObject)
{
if (gameObject != null && pool != null)
{
gameObject.SetActive(false);
gameObject.transform.SetParent(transform);
pool.Push(gameObject);
}
}
private void OnDestroy()
{
if (pool == null)
{
return;
}
while (pool.Count > 0)
{
var obj = pool.Pop();
Destroy(obj);
}
}
}
Your answer
Follow this Question
Related Questions
Instantiate is throwing my throwing my objects? 1 Answer
Problems with spawning items that the players can pick up - Unet 0 Answers
Uncontrollable platform spawning. 1 Answer
Enemies spawn on top of each other(C#)(Unity) 1 Answer
How do I spawn an object under another moving object at random in C#? 1 Answer