5 hours ago, ethancodes said:This is a problem because DestroyAdjacent is called from the DestroyBrick() in the Explosive Brick class. DestroyAdjacent calls FindObjectAt, thus we have FindObjectAt() -> DestroyBrick() -> DestroyAdjacent() -> FindObjectAt() -> DestroyBrick() -> and so on and so on.
This was the problem, you made a loop. Code fixed:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosiveBrick : Brick {
private GameObject boardManager;
private Vector3 currentPosition;
public override void Update ()
{
timer += Time.deltaTime;
//timer determines when the brick will move
if (timer >= delay)
{
transform.Translate(0.0f, -1.0f,0.0f);
timer = 0;
currentPosition = this.gameObject.transform.position;
}
}
public override void DestroyBrick ()
{
if (timesHit >= maxHits) {
breakableCount--;
PuffSmoke ();
DestroyAdjacent ();
levelManager.BrickDestroyed ();
Destroy (gameObject);
} else {
LoadSprites ();
}
}
//Lets make it so this destroys a brick
public void DestroyObjectAt (float InX, float InY)
{
RaycastHit2D hit = Physics2D.Raycast (new Vector3 (InX, InY, -0.02f), Vector3.forward, 0.02f);
if (hit.collider != null) {
//Checking that it isn't a explosive brick is a easy fix for now.
//Accurately aiming your ray will be better. Remember that the ray hits in unity space
if (hit.collider.tag == "Breakable" && !(hit.collider.GetComponent<Brick>() is ExplosiveBrick)) {
//This will now call destroy on a brick IF it is hit.
hit.collider.GetComponent<Brick> ().DestroyBrick ();
}
}
}
//This will destroy all the bricks now
public void DestroyAdjacent ()
{
//The rays actually hit this object also so lets expand a bit
//check right
DestroyObjectAt(currentPosition.x + 1f, currentPosition.y);
//check above
DestroyObjectAt(currentPosition.x, currentPosition.y +1f);
//check left
DestroyObjectAt(currentPosition.x - 1f, currentPosition.y);
//check below
DestroyObjectAt(currentPosition.x, currentPosition.y -1f);
//Check up and right
DestroyObjectAt(currentPosition.x + 1f, currentPosition.y + 1f);
//check down and right
DestroyObjectAt(currentPosition.x + 1f, currentPosition.y - 1f);
//check up and left
DestroyObjectAt(currentPosition.x - 1, currentPosition.y + 1f);
//check down and left
DestroyObjectAt(currentPosition.x - 1, currentPosition.y - 1);
}
}
In short I turn the "FindObject" into "DestroyObject" so that the "DestroyAdjacent" destroys each in turn.
I also check that it doesn't use DestroyBrick again on the explosion object.
Also your rays aren't aimed well you just use +1. This means the ray also hits the explosion block because. Remember that you now use actual Position as in the point where the object is in the world.
Because your sprite isn't centered, it starts from the corner, +1 to the right means you miss and -1 to the left means you almost miss the object to the left:
So you keep missing all the blocks except for the explosive block itself. To fix this either adjust the values of fix the pivot point.