So each time one of the walls get into the range of “col” they should be added to the list “radius” and when the ball move too far away they should be removed from the list and not therefore not destroyed when Explosion is run.
This works for BW1 but when I reach BW2 I reach BW2 i get an null error, saying that I’m trying to access a gameobject I already destroyed. I’ve dragged them both into the scene from a prefab I created earlier if that matters, they are both tagged with “bw”. Also, if I reach BW2 first I won’t get the error but neither will it destroy that wall.
So my questions would be:
How can I remove BW1 from the scene without destroying the gameobject so that I can remove additional BWs later? (or destroy the gameobject as long as I can do it on several BWs)
How can I remove BW2? since the code I have doesn’t seem to affect it.
There are several conceptual/design problems with your code, as far as we can see from what you shared.
This expression: GameObject.FindWithTag("bw"); will return a single object tagged “bw”. But it is not guaranteed to be any specific object in any specific order.
You can use GameObject.FindGameObjectsWithTag("bw"); instead, which is better, but this brings us to the next design problem - why are you looking for these objects in the first place? You already have them in your radius collection, and judging by your logic - you’re only interested in those that are already in that collection. So, why not just iterate through the collection and destroy those elements instead?
Destroying the objects isn’t enough, you also need to remove the object from the radius container, otherwise, next time you run the explosion, the game engine will attempt to destroy those objects again.
Using SetActive instead of actually destroying is indeed better for the general performance of the game. Regarding the timing you need for this function - try something like this:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Hide(float timeToWait) {
Invoke("HideMe", timeToWait);
}
void HideMe() {
gameObject.SetActive(false);
}
}
So I’m assuming ‘col’ is your ball. If it’s not already on it, you could add your collision script to this gameobject and then you can get a reference to the other ‘wall’ object from the 2Dcollision method (otherObject is automatically assigned) and add it a list or do whatever you want to do with it:
ps. you’ll need to set up the rigidbody’s correctly too (isKinematic values etc). Also rather than destroying them, use SetActive(false) so garbage collection doesnt kick in.