Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
1
Question by Internetman · Mar 12, 2016 at 02:01 PM · c#instantiateprefabdestroypower up

Destroy prefabs after they have been instantiated (C#)

Hello my friend who is reading this! I got a problem with some of my code. I have created a power up prefab that is supposed to destroy all enemy prefabs that are out on the map. I'm spawning out new enemies every 3 to 5 seconds. Now when I run over the power up, it only destroys the enemies that were instantiated before the power up was used and spawned.

How can I destroy all enemies out on the map including the new ones that spawned in after the power up spawns in?

Code for picking up the power up: (Note that the power up is used directly when you trigger/collide with it)

 using UnityEngine;
 using System.Collections;
 
 public class PickUpScript : MonoBehaviour 
 {
     void OnTriggerEnter2D(Collider2D col)
     {
         if(col.gameObject.tag == "PowerUp1")
         {
             Destroy(GameObject.FindGameObjectWithTag("EnemyBouncing"));
             Destroy(GameObject.FindGameObjectWithTag("EnemyFollow"));
             Destroy(GameObject.FindGameObjectWithTag("PowerUp1"));
         }
 }

Code for spawning out enemies:

 using UnityEngine;
 using System.Collections;
 
 public class EnemySpawn : MonoBehaviour 
 {
     // EnemyPrefabs
     public GameObject EnemyBouncingPrefab;
     public GameObject EnemyFollowPrefab; 
 
     //Show where spawn is prefab
     public GameObject ShowEnemySpawn;
 
     // Array of spawn points 
     public Transform[] spawnPoints;         
     
     // Borders
     public Transform borderTop;
     public Transform borderBottom;
     public Transform borderLeft;
     public Transform borderRight;
 
 
 
     void Start () 
     {
         // Starts a coroutine function for spawning bouncing enemies
         StartCoroutine(SpawnBouncingEnemy());
 
         // Spawn only one follow enemy
         InvokeRepeating("SpawnEnemyFollow", Random.Range(2, 5), 0);
     }
 
     
     // Spawn a Bouncing enemy
     IEnumerator SpawnBouncingEnemy() 
     {
         //Wait 3 seconds when game starts to spawn a ball
         yield return new WaitForSeconds(Random.Range(3, 5));
 
         while(true)
         {
             //Calls the function to set random position
             Vector2 spawnPoint = RandomPointWithinBorders();
             
             // Show spawn location for one second
             Object marker = Instantiate(ShowEnemySpawn, spawnPoint, Quaternion.identity);
             yield return new WaitForSeconds(1);
             Destroy(marker);
             
             // Spawn enemy
             Instantiate(EnemyBouncingPrefab, spawnPoint, Quaternion.identity);
             yield return new WaitForSeconds(Random.Range(4, 6));
         }
         
     }    
 
     Vector2 RandomPointWithinBorders()
     {
         //Code that will spawn a bouncing ball and ShowSpawn at a random position inside the borders 
         Vector2 random = new Vector2();
         random.x = (int)Random.Range(borderLeft.position.x, borderRight.position.x);
         random.y = (int)Random.Range(borderBottom.position.y, borderTop.position.y);
         return random;
     }
 
 
     void SpawnEnemyFollow()
     {
         // Find a random index between zero and one less than the number of spawn points.
         int spawnPointIndex = Random.Range (0, spawnPoints.Length);
 
         
         // Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
         Instantiate (EnemyFollowPrefab, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
     }
 }

I'm so grateful for every help that I can get! You guys are the best! Been trying to solve this for ages, but haven't found any great answers yet.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by TreyH · Mar 12, 2016 at 02:44 PM

Instead of using the tag system, you might want to just keep track of your spawned enemies:

 using System.Collections.Generic;

So we'll just add new enemies to a list:

 // Keep track of enemies we've created across all spawners
 public static List<GameObject> activeEnemies;
 
 // Start
 void Awake()
 {
     // Create the list
     activeEnemies = new List<GameObject>();
 }
 
 // Destroy all existing enemies
 public static void DestroyActiveEnemies()
 {
     // Prevent ourselves from tinkering with a List during its enumeration
     int currentCount = activeEnemies.Count;
 
     // Go through and destroy each one
     for (int k=0; k<currentCount; k++)
     {
         Destroy(activeEnemies[k]);
     }
 
     // Clear the list up to this point
     activeEnemies.RemoveRange(0, currentCount);
 }

So for each of your spawning functions, add the new enemy to this list:

 // Instantiate
 GameObject newEnemy = (GameObject) Instantiate(EnemyBouncingPrefab, spawnPoint, Quaternion.identity);
 
 // Add them to our list
 activeEnemies.Add(newEnemy);
 
 // Yield for the coroutine (Note that this will cause GC (due to the "new" part),
 // but you can declare a WaitForSeconds instance to prevent this
 yield return new WaitForSeconds(Random.Range(4, 6));


Causing your pickup script's Trigger code to become:

 public class PickUpScript : MonoBehaviour 
 {
     void OnTriggerEnter2D(Collider2D col)
     {
         if(col.gameObject.tag == "PowerUp1")
         {        
             // Call the function we just wrote
             EnemySpawn.DestroyActiveEnemies();
         }
     }
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Internetman · Mar 12, 2016 at 06:40 PM 0
Share

You're a genius! It worked, thank you again!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

127 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Unable to destroy instantiated prefab during OnMouseExit,Unable to Destroy previously instantiated object OnMouseExit() 0 Answers

Instantiate and destroy an object with the same key 1 Answer

How do I destroy a Instantiated UI Image that is a prefab but is pused on the Canvas? 0 Answers

Trying to replace 2 objects. Destroying assets is not permitted to avoid data loss. 0 Answers

What is Casting in Unity ? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges