Search code examples
c#unity-game-enginescene-manager

How can I change scenes when 2 different player objects are inside a door's trigger at the same time?


There are player GameObjects which must have different tags: "Player1" and "Player2". There is a door GameObject, where if both players are inside the door's trigger, the scene will be changed.


Solution

  • You could have 2 bools, one for each player, that changes true when entering the door trigger, and false when exiting.

    Then in an Update() on the script, have an if statement that performs the SceneManager function when both bools are true.

    Hope I answered your question, here is a script I made and tested your situation on:

    public class DoorController : MonoBehaviour {
    
        bool p1IsTouching = false;
        bool p2IsTouching = false;
    
        void Update() {
            if (p1IsTouching && p2IsTouching) {
                //do SceneManager stuff
            }
        }
    
        void OnTriggerEnter2D(Collider2D other) {
            if (other.gameObject.tag == "Player1") { p1IsTouching = true; }
            if (other.gameObject.tag == "Player2") { p2IsTouching = true; }
        }
    
        void OnTriggerExit2D(Collider2D other) {
            if (other.gameObject.tag == "Player1") { p1IsTouching = false; }
            if (other.gameObject.tag == "Player2") { p2IsTouching = false; }
        }
    }