Search code examples
c#unity-game-enginecollision

Change scene after collision of different objects


I have 10 cylinders in the sky and I want that when all 10 hit the ground (plane) I can change the scene to a different one.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.SceneManagement;
 
 public class contactGround : MonoBehaviour
 {
     void OnCollisionEnter(Collision col){
         if(col.gameObject.name == "Cylinder" && col.gameObject.name == "Cylinder (1)"
         && col.gameObject.name == "Cylinder (2)" && col.gameObject.name == "Cylinder (3)"
         && col.gameObject.name == "Cylinder (4)" && col.gameObject.name == "Cylinder (5)"
         && col.gameObject.name == "Cylinder (6)" && col.gameObject.name == "Cylinder (7)"
         && col.gameObject.name == "Cylinder (8)" && col.gameObject.name == "Cylinder (9)"){
             Debug.Log("Collision detected");
             SceneManager.LoadScene(16);  
         }
     }
 }

i try that but doesn't work. any idea??


Solution

  • How can one single object (col.gameObject) have 10 different names at the same time? ;)

    You rather want to keep track of which objects collided and count how many have collided. Them once you reach 10 go to the next scene

    public class contactGround : MonoBehaviour
    {
        private HashSet<GameObject> collided = new HashSet<GameObject>();
    
         void OnCollisionEnter(Collision col)
         {
             if(col.gameObject.name.StartsWith("Cylinder") && !collided.Contains(col.gameObject))
             {
                 Debug.Log("Collision detected");
                 collided.Add(col.gameObject);
    
                 if(collided.Count >= 10)
                 {
                     SceneManager.LoadScene(16); 
                 } 
             }
         }
     }
    

    Though in general rather do not go by me but give them a certain Tag like e.g. Cyllinder and then rather check

    if(col.gameObject.name.CompareTag("Cylinder") && !collided.Contains(col.gameObject))