- Home /
Why is my Destroy not working in my foreach loop?
I have a sprite that I use 2d Destruction on it: it creates multiple fragments of the sprite. I want to destroy these fragments when it reaches a certain height, but they are not destroyed even if the condition is true.
Here is the code:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Explodable))]
public class ExplodeOnClick : MonoBehaviour {
private Explodable _explodable;
private GameObject[] _fragments;
void Start()
{
_explodable = GetComponent<Explodable>();
_fragments = GameObject.FindGameObjectsWithTag("Objective");
}
void Update()
{
DestroyFragments();
}
void OnMouseDown()
{
_explodable.explode();
ExplosionForce ef = GameObject.FindObjectOfType<ExplosionForce>();
ef.doExplosion(transform.position);
}
void DestroyFragments()
{
foreach(GameObject frags in _fragments)
{
if(frags.transform.position.y < -40)
{
Destroy(frags);
}
}
}
}
Thank you for your time.
hum, you instantiate the fragments when the sprite explode? If this is the case, try searching for fragments after explosion
void On$$anonymous$$ouseDown()
{
_explodable.explode();
ExplosionForce ef = GameObject.FindObjectOfType<ExplosionForce>();
ef.doExplosion(transform.position);
_fragments = GameObject.FindGameObjectsWithTag("Objective");
}
following the case, if you search it on start, where dont instantiated it yet, the _fragments
will keep empty forever
Answer by Vicarian · Feb 06, 2019 at 06:56 PM
In C#, you're not supposed to modify a collection when using a foreach loop. Use a for loop instead. Further, the Destroy doesn't happen immediately. I'm not quite sure of the timing, but it takes at least one frame before the Destroy starts processing. So the loop you invoke Destroy happens say in frame 0, while the destruction actually starts happening in frames starting at 1, and may not complete within the next frame. At least that's been my experience.
Answer by Eliasar · Feb 06, 2019 at 07:20 PM
I would suggest that you utilize the Particle System to do this instead of having to keep up with an array of GameObjects. They can even have collision and will handle destruction based on timer or velocity.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to add score after destroying object? 1 Answer
Delete object only when a certain cursor is enabled 1 Answer