Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question box colliders are affecting collisionDetection script

Discussion in 'VR' started by levysn, Sep 19, 2023.

  1. levysn

    levysn

    Joined:
    Aug 10, 2023
    Posts:
    5
    hello all! so I am currently working on a feature in a project that essentially counts the amount of objects that have entered a trigger area and outputs some text when all 3 objects have entered it. However, I have come across an odd issue. Initially I had 3 objects (the objects that are being placed into the trigger area) with box colliders added on to them with on trigger checked. This caused the object to fall through the floor on the scene. To fix this I:

    - added one additional box collider to each object without trigger checked
    - also added an additional collider to the trigger area that the objects were hitting as the same thing was happening there

    the question: now, the script is checking for collisions, but the number of collisions is inconsistent. Sometimes when 2 items hit the trigger area the text outputs, and sometimes this happens when only 1 does. Here is the script I wrote, if anyone has any clue on how to fix this or where I am going wrong that would be great! :

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using TMPro;
    6. using UnityEditor;
    7.  
    8. public class CrateInteraction : MonoBehaviour
    9. {
    10.     public GameObject holeTrigger;
    11.     public TextMeshProUGUI displayText;
    12.     private bool allCratesDropped = false; // Track if all crates are dropped
    13.     private int cratesDropped = 0;
    14.  
    15.  
    16.     private void OnTriggerEnter(Collider other)
    17.     {
    18.         if (other.gameObject == holeTrigger && !allCratesDropped) // Check if not all crates are dropped
    19.         //if( other.gameObject.CompareTag("Crate") == holeTrigger)
    20.         {
    21.             Debug.Log("Crate detected");
    22.             cratesDropped++;
    23.             //displayText.text = cratesDropped + " crates have been dropped. ";
    24.  
    25.             if (cratesDropped >= 8) // to account for extra colliders.
    26.             {
    27.                 Debug.Log("All crates have been dropped");
    28.                 displayText.text = "Congratulations! You have dropped all crates.";
    29.                 allCratesDropped = true; // Set the flag to indicate all crates are dropped
    30.                 Debug.Log("number of crates counted= " + cratesDropped); // not printing?
    31.    
    32.             }
    33.         }
    34.     }
    35. }
    36.