- Home /
How to find and destroy gameobject with same tag one by one
Hi, i would like to ask if anybody knows a code that at first will find objects to their transform by using the gameobjectfindtag(), the idea here is to find and destroy the gameobject taged as enemy then go to the next object with its transform then destroy again the object, abd the code keed doing this until no gameobject is left in the scene, all gameobject is taged as enemy. Wish i could get help here, thanks alot.
Answer by Llama_w_2Ls · Jul 30, 2020 at 08:43 AM
void DestroyEnemiesOneByOne()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
//Makes a list of all the gameObjects with the tag 'Enemy'
for (int i = 0; i < enemies.Length; i++)
{
Destroy(enemies[i], 0.5f);
//Destroys every item in the list one by one,
//with a delay of 0.5 secs
}
}
Answer by Maggiethegsd · Jul 30, 2020 at 12:22 PM
Maybe make a list of all the enemies in the scene, and then destroy them one by one with a for statement. something like this should work fine :
using UnityEngine;
public class enemyKiller : MonoBehaviour
{
GameObject enemiesInScene[];
void Start()
{
enemiesInScene = new List<GameObject>();'
enemiesInScene.Add(GameObject.FindObjectsWithTag("Enemy"));
}
void FixedUpdate()
{
for (int x =0; i < enemiesInScene.lenght; x ++)
{
Destroy (enemiesInScene [x], 2f);
\\ the 2f is inserted so as to add some delay to killing/destroying the
\\enemies, you can insert whatever number you want!
}
}
}
Your answer
Follow this Question
Related Questions
Camera rotation around player while following. 6 Answers
Shuriken Particles to follow a target gameobject 0 Answers
GameObject follow animation 1 Answer