Reputation: 25
I am doing a script that instantiate prefab in a list of prefab and then destroy them after a delay, but I want to re instantiate them if a enter into the trigger I tried something with a bool
and a condition but that doesn't work.
There is the code :
public class CreateObject : MonoBehaviour
{
public GameObject[] Prefab;
public Transform[] spawnPoint;
private int i = 0;
private int j = 0;
private int k = 0;
private float delay = 5f;
private float delaySound ;
public bool destroyOrNot;
void OnTriggerEnter(Collider other)
{
// fonction on l'on fait apparaitre les objets de la liste selon son empty
while (i<Prefab.Length && j < spawnPoint.Length )
{
GameObject clone = Instantiate(Prefab[i] , spawnPoint[j].position, spawnPoint[j].rotation);
Debug.Log("Detruire");
destroyOrNOt = Destroy(clone ,delay);
i++;
j++;
k++;
if (destroyOrNot = true)
{
while (i < Prefab.Length && j < spawnPoint.Length )
{
GameObject clone = Instantiate(Prefab[i] , spawnPoint[j].position, spawnPoint[j].rotation);
Debug.Log("Detruire");
destroyOrNot = Destroy(clone ,delay);
i++;
j++;
k++;
}
}
}
}
That doesn't work and it tell me that we cant implicitly convert void to bool
!
So please do you have any idea how can I do the thing ?
I am new in unity so maybe its something easy to do but I didn't figured how can I make it.
Thank you !
Upvotes: 0
Views: 1066
Reputation: 75
First of all Destroy() method does not return any bool value so you have convertation mistake.
I'm not 100% sure what exactly you tried to do in this code snippet but I do not recommend you to "re-instantiate" deleted prefabs. Prefab instantiation (as wel as destruction) is very expensive operation and will cause perfomance issues.
If you use several REUSABLE objects you should using OBJECT POOLING.
The idea is simple. Basically you spawn all prefabs you need at start (when you loaded your level\started event\etc.) and disable all these spawned objects.
When you need one of them you just enable this object and reconfigure it (change positions, settings). When you don't need object anymore - just disable it and take back to pool (some kind of list\collection).
And once you are COMPLETELY done with all these objects (dont need any of them anymore) - then Destroy all the pool.
This is the right way to deal with "reusable" objects.
You can learn more about object pooling here: Object pooling in unity
Upvotes: 2