Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

3 objects at the same time????

Discussion in '2D' started by Cynicave, Jun 19, 2022.

  1. Cynicave

    Cynicave

    Joined:
    Oct 18, 2021
    Posts:
    2
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class door : MonoBehaviour
    7. {
    8.     private bool enterAllowed;
    9.  
    10.  
    11.     private void OnTriggerEnter2D(Collider2D collision)
    12.     {
    13.         if (collision.GetComponent<player1>())
    14.         {
    15.             if (collision.GetComponent<player2>())
    16.             {
    17.                 enterAllowed = true;
    18.             }
    19.         }
    20.     }
    21.     private void OnTriggerExit2D(Collider2D collision)
    22.     {
    23.         if (collision.GetComponent<player1>() || collision.GetComponent<player2>())
    24.         {
    25.             enterAllowed = false;
    26.         }
    27.     }
    28.  
    29.     private void Update()
    30.     {
    31.         if (enterAllowed && Input.GetKey(KeyCode.Return))
    32.         {
    33.             SceneManager.LoadScene("level2");
    34.         }
    35.     }
    36.  
    37.  
    38.  
    39.  
    40. }
    41.  
     
  2. Cynicave

    Cynicave

    Joined:
    Oct 18, 2021
    Posts:
    2
    hi I am working on a game where you have to open a door but the door is too heavy for 1 player so you have to be 2. I do not understand how to detect when 3 or more objects collide !!! I have tried to write some code but it does not work !!
     
  3. microbrewer

    microbrewer

    Joined:
    Jun 6, 2020
    Posts:
    12
    The trigger enter and exit callbacks are called for each individual collider that enters/exits the one you are on. So assuming that player1 and player2 are attached to two different game objects, line 17 will never be executed.

    Instead, if you want to check if two or more colliders currently overlap with this one, a straightforward way is to increment a counter when an object enters and decrement it when one exits. Then check the current counter value. If you need to retain references to the objects, store them in a list and add/remove them accordingly.
     
    MaxwellTan likes this.