At the moment if there’s a glass block in the bomb’s radius, it will destroy the bomb and the glass block. My problem is that if there’s a block that isn’t glass the bomb won’t “explode” until something comes into it’s radius. I have a FixedUpdate which handles the counting down of the bomb and makes the bomb explode if it “isn’t colliding”. See code:
You’ll definitely want to use some flavor of ray casting instead of collision; It models your solution better (easier to understand) and will give you better performance. I would also prefer a Coroutine (Unity - Manual: Coroutines) over FixedUpdate() here for the same reasons.
The gist of Cherno’s suggestion is correct, but in 2D you’ll want to use one of the Physics2D overlap functions. Here’s some sample code (warning: untested):
class Bomb : MonoBehaviour {
public float explosionDelay;
public float explosionRadius;
public void BeginCountdown() {
StartCoroutine(Countdown());
}
IEnumerator Countdown() {
yield return new WaitForSeconds(explosionDelay);
Explode();
}
void Explode() {
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, explosionRadius);
foreach (Collider2D collider in colliders) {
Block block = collider.GetComponent<Block>();
if (block != null && collider.gameObject.tag == "glass") {
block.Explode();
}
}
Destroy(this.gameObject); // Remove the object this script is attached to. The "this" keyword is optional, but I think it reads a little more clearly.
}
}
To make a bomb explode, you simply get a reference to the Bomb script and call the BeginCountdown() function, like so:
I would also suggest using the following pattern of adding an enumeration-type variable to represent the material in your block class, as opposed to relying on tags:
class Block : MonoBehaviour {
public enum Materials { None, Glass, Stone }; // Add your other block types here.
public Materials material; // Now for each of your block objects, you can assign this value from a drop down in the inspector (instead of having to make a tag for each material).
public Explode() {
// Put whatever you want to happen when the block explodes here!
Destroy(this.gameObject);
}
}
If you implement this, then the code that checks for a glass block in the Bomb class would change to