I have a 6x6x8 (about 288) stack of rigidbody cubes set up on my simple scene and i have a player controlled object that can either run into those cubes, making them topple or you can hit a key and explode causing the cubes to fly.
in the explosion loop in my player code, I paint the cubes red if they were directly in the blast radius and tell those specific cubes they have been hit. In the cube behavior script I have an OnCollisionEnter that checks if they have been hit by the explosion, and if they have, paint them green only if they hit the ground.
The code works fine but it gets really choppy for a few seconds during the initial blast. If i take out the block behavior code, it runs just fine. Im sure there is a more efficient way to do what im doing but I am not sure what it is. The code in question is below.
How can i do the OnCollisionEnter better?
My player code:
Vector3 explosionPos = myTransform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPos, explosionRadius);
foreach(Collider hit in colliders)
{
if(!hit)
continue;
if(hit.rigidbody)
{
hit.rigidbody.AddExplosionForce(explosionPower, explosionPos, explosionRadius, 3.0f);
if(hit.collider.gameObject.tag == "Block"){
hit.GetComponent<BlockBehavior>().HasBeenHit(true);
}
hit.renderer.materials[0].color = Color.red;
}
}
My block behavior code snippet:
void OnCollisionEnter(Collision col){
if(hasBeenHit){
if(col.gameObject.name == "Ground"){
renderer.materials[0].color = Color.green;
}
}
}
public void CanCollect(bool col){
hasBeenHit = col;
}