- Home /
Produce Collision Though Code
I have a scene with a large brick wall. Each brick is a prefab with a box collider. Upon shooting projectiles at the wall I call OnCollisionEnter() and add a rigidBody component to the brick that was hit. I am doing this so there aren't an unnecessary amount of rigidbodies in the scene. After a brick is hit once, subsequent hits will knock it out of place as expected.
I would like to have the bricks get knocked out on the first hit, and to take the OnCollisionEnter.Collision information and add a force to the brick right after the rigidbody component has been added. Is this a common technique to save some resources or has anyone else tried something like this?
I've tried AddForce and AddRelativeForce on the brick rigidbody but to no avail.
My current OnCollisionEnter() method on a script attached to the projectile.
void OnCollisionEnter(Collision brick)
{
Debug.Log(brick.gameObject.tag);
if (brick.gameObject.tag == "Brick")
{
brick.gameObject.GetComponent<MeshRenderer>().material.color = Color.red;
if (!brick.gameObject.GetComponent<Rigidbody>())
{
Rigidbody bRB = brick.gameObject.AddComponent<Rigidbody>();
bRB.mass = 100;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612034443im_/https://answers.unity.com/themes/thub/images/avi.jpg)