Too much clones of my gameobject in Unity (How to fix this?)

I don’t know why, but my idea was to spawn a gameobject called Fire 5 times with delay in random positions with Vector2. And after delay, each one of them get’s destroyed and then other clones will spawn. However there is too much clones spawning at the beginning of the game. Even if I tried to spawn just one newFire, loads of clones would appear in the Gameobject section.

Please tell me the solution.

when I tried to spawn 6 fire in circulation

The code for spawning 6 fire in circulation:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnController : MonoBehaviour
{
    public GameObject Fire;
    public int count = 1;
    public int maxFireCount = 6;
    public float spawnDelay = 6.0f;
    public float despawnDelay = 2.0f; 

    private List<GameObject> spawnedFires = new List<GameObject>();

    void Start()
    {
        StartCoroutine(FireDrop());
    }

    IEnumerator FireDrop()
    {
        for (count = 1; count < maxFireCount; count++)
        {

                float xPos = Random.Range(-5f, 5f);
                float yPos = Random.Range(-5f, 5f);

                Vector2 spawnPosition = new Vector2(xPos, yPos);

                GameObject newFire = Instantiate(Fire, spawnPosition, Quaternion.identity);
                spawnedFires.Add(newFire);
                yield return new WaitForSeconds(despawnDelay);
                Destroy(newFire, 1);
                Debug.Log(gameObject + " hasn't beed destroyed yet!"); 

            yield return new WaitForSeconds(despawnDelay);

            GameObject[] remainingFireObjects = GameObject.FindGameObjectsWithTag("Clone");
            foreach (var fireObject in remainingFireObjects)
            {
                Destroy(fireObject, 1);
            }

            spawnedFires.Clear(); 

            yield return new WaitForSeconds(spawnDelay);
        }
    }
}

The first thing to note is that this script actually spawns 5 fires, because count begins from 1 and goes to 5.

Beyond that, I run the script in an empty scene and works fine for me, maybe you have added that script in the Fire gameobject, so every fire spawned runs it again?

If you add the SpawnController script to its own gameobject in the scene and the prefabs that have the fire script don’t have the SpawnController script it should work.

2 Likes

Thx bro, really appreciate your advice.