unity-game-enginedestroyspawning

Unity3D: delete spawn objects


I have a 2d game where there is an original enemy ninja.
I created spawning script to clone my original ninja. I then placed it on my main camera to make my ninja clone spawn within the main camera view. My original ninja also has a script that after a few seconds it will delete.
I realize that deleting my original ninja cause my clone ninjas not appear, but I want to delete any cloned objects so that I won't over run my project.
Is there a way were I can delete the spawn clone ninjas without touching the original ninja. Or hiding my original ninja in the inspector without hiding the spawn clones.
Here's my destroy ninja code:

private IEnumerator Killninja() {

   yield return new WaitForSeconds (4f);
     Destroy (gameObject);
}

    void Update () {
       StartCoroutine (Killninja ());
    }

Solution

  • If you don't want your original Ninja to be in the scene, don't have it in the scene. Drag it from the scene into the Project Explorer. This will create a Prefab of the Ninja. You can then delete the Ninja from the scene.

    Now have a ObjectSpawner.cs script which has the task of spawning a Prefab. Ninja, like:

    public class ObjectSpawner : MonoBehaviour
    {
        public GameObject prefab;
    
        void Start()
        {
            GameObject.Instantiate(prefab, transform.position, transform.rotation);
        }
    }
    

    Assign ObjectSpawner to an empty GameObject in the Scene, and assign the Ninja Prefab you created earlier to its prefab field. This will spawn one Ninja as soon as the game starts, at the position of your NinjaSpawner object.

    Your Ninja.cs script will be responsible for destroying the Ninja once its time is up:

    public class Ninja : MonoBehaviour
    {
        void Start()
        {
            StartCoroutine(DestroyDelayed());
        }
    
        IEnumerator DestroyDelayed()
        {
            yield return new WaitForSeconds(4f);
            Destroy(gameObject);
        }
    }
    

    Make sure that script is assigned to your Ninja object.