- Home /
 
Diasble collision between exsisting gameObjects and newly created ones

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";
 
     }
         
 }
 
              Answer by mjc33 · Feb 14, 2020 at 10:24 PM
A simple approach would be to put each "piece" game object into a different layer during creation and disable collisions for that layer in the collision matrix in project settings:
Would just need to add this line of code before adding the Rigidbody component
  piece.layer = [int layer number];
 
               eg.
 piece.layer = 3;
 
              I have tried this out, I have put every piece to one separate layer called "pieces" and then removed layer collision, but still does not work... 
I have tried to use Physics.IgnoreLayerCollision and it worked, thank you
Your answer