- Home /
How to destroy gameobject in hierarchy with a bool list.
Here I have a foreach function that outputs all the gameobject with the "enemy" tag in the hierarchy. Each "enemy" tag gameobject has a static bool candestory. How do I destroy those gameobjects in hierarchy when the bool is true?
foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject))) {
if(obj.CompareTag("enemy")){
Debug.Log(obj.name);
list1.Add(obj);
}
public class Enemy : Character {
public static bool shoulddestroy= false;
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player")){
shoulddestroy = true;
print("you should destory on next load"+ other.gameObject);
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player")){
print("im out"+ other.gameObject);
}
}
Answer by HellsHand · Apr 22, 2021 at 08:20 PM
You shouldn't use public static bool shoulddestroy
if there are multiple enemies, since this will cause all instances of the script to share the value, leave off the static
. As far as destroying the object you can just add:
if(shoulddestroy)
{
int index = 0;
foreach(GameObject obj in list1)
{
if(obj == gameObject) break;
else index++;
}
list1.RemoveAt(index);
Destroy(gameObject);
}
to your Update()
of the Enemy
script. This will destroy the object and remove it from the list.
Hello, thank you so much for pointing out the static bool. now I remove the static on the bool statement but run into a different issue. How do I avoid the bool shoulddestory being reset after reload the scene. I don't think I can use DontDestroyOnLoad on the Enemy script because it attach to multiple enemies. so right now I have the following on a different script. But the enemy.shoulddestroy reset to false after reload the scene. please help
void Awake() {
if (Instance == null)
{
DontDestroyOnLoad(gameObject);
Instance = this;
}
else if (Instance != this)
{
Destroy(gameObject);
}
}
void Start()
{
foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
{
if(obj.CompareTag("enemy")){
Debug.Log(obj.name);
list1.Add(obj);
}
}
}
void Update()
{
foreach(GameObject obj in list1)
{
if(obj == gameObject && enemy.shoulddestroy)
Destroy(gameObject);
}
Answer by nursedayuksel · Apr 22, 2021 at 07:19 PM
You can try something like this:
if (other.gameObject.CompareTag("Player")){
shoulddestroy = true;
for (var i = 0; i < list1.Length; i++) {
Destroy(list1[i]);
}
print("you should destory on next load"+ other.gameObject);
}
This would destroy all enemy gameobject disregard their boolean value, but I think I have an idea.