0
\$\begingroup\$

I have public variables which I populate through the inspector. One script is attached to a single object and the other script has a gameObject array property. Please see below:

public class GamePlayScript : MonoBehaviour {

public BallScript ballScript;
public BrickGroupsScript brickGroupsScript;


// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}
}

BrickGroupsScript contains an array of bricks which has a isBroken bool property. Also the above code is attached to an empty game object. How can I detect when the ball game object is in contact/collided with a brick with isBroken = true?

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

As far as I know, you can't detect collision without a script implementing OnCollisionEnter.

You can attach the following script to all of your bricks which will dispatch/raise an event when something collided into it :

public class Brick : MonoBehaviour
{
    public event System.EventHandler OnTouched;

    void OnCollisionEnter(Collision collision)
    {
        if ( OnTouched != null )
            OnTouched( this, System.EventArgs.Empty );
    }
}

Then, supposing you have an array of Bricks, you can subscribe to the OnTouched event :

[SerializeField]
private Brick bricks ;

private void Start()
{
    for( int brickIndex = 0 ; brickIndex < bricks.Length ; ++brickIndex )
        bricks[brickIndex].OnTouched += OnBrickTouched;
}

private void OnBrickTouched( object sender, System.EventArgs e )
{
    Brick brick = (Brick) sender;
    // Do something with your brick
}

EDIT : After reading again your question, you want to detect collision on the ball. The principle is the same, check the scripts below.

public class BallEventArgs : EventArgs
{
    public BrickScript Brick;
    public BallEventArgs(string brick)
    {
        Brick = brick;
    }
}

public class BallScript : MonoBehaviour
{
    public event System.EventHandler<BallEventArgs> OnBrokenBrickTouched ;

    void OnCollisionEnter(Collision collision)
    {
        Brick touchedBrick = collision.collider.GetComponent<Brick>();

        if ( touchedBrick != null && touchedBrick.isBroken && OnBrokenBrickTouched != null )
            OnBrokenBrickTouched ( this, new BallEventArgs(touchedBrick) );
    }
}

// ........

public class GamePlayScript : MonoBehaviour {

    public BallScript ballScript;
    public BrickGroupsScript brickGroupsScript;


    // Use this for initialization
    void Start () {
        ballScript.OnBrokenBrickTouched += OnBrokenBrickTouched ;
    }
    private void OnBrokenBrickTouched( object sender, BallEventArgs e )
    {
        BallScript ball = (BallScript) sender;
        BrickScript brick = e.Brick;
        // Do something with your ball and your brick
    }
}
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .