I make a game where the robot should hit the cube and then the cube exploids to a lot of small cubes and gets destroyed after some time. The problem is that I do not know how to neglect the collison between newly generated small cubes and all other rigidbodies. I have tried to enable isTrigger for them but does not seem to work. Any ideas?
The code is also included.
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == "Obstacle")
{
Debug.Log("hit");
Explosion();
}
}
void Explosion ()
{
gameObject.SetActive(false);
for (int x = 0; x < cubesAmount; x++)
{
for (int y = 0; y < cubesAmount; y++)
{
for (int z = 0; z < cubesAmount; z++)
createPieces(x, y, z);
}
}
Vector3 explPos = transform.position;
Collider[] colliders = Physics.OverlapSphere(explPos, radius);
foreach (Collider hit in colliders)
{
Rigidbody rb2 = hit.GetComponent<Rigidbody>();
if (rb2 != null)
{
rb2.AddExplosionForce(Random.Range(explosionMin, explosionMax), transform.position, radius);
}
if (hit.gameObject.name == "piece")
{
//hit.isTrigger = true;
Destroy(hit.gameObject, 5f);
}
}
}
void createPieces(int x, int y, int z)
{
GameObject piece;
piece = GameObject.CreatePrimitive(PrimitiveType.Cube);
piece.transform.position = transform.position + new Vector3 (pieceSize * x , pieceSize * y, pieceSize * z); // setting position
piece.transform.localScale = new Vector3 (pieceSize, pieceSize, pieceSize); //setting scale of the object
piece.AddComponent<Rigidbody>();
piece.GetComponent<Rigidbody>().useGravity = true;
piece.GetComponent<Rigidbody>().mass = pieceSize;
piece.GetComponent<Renderer>().material = material;
piece.GetComponent<Collider>().isTrigger = true;
piece.name = "piece";
}
}