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.

OnTriggerEnter alternative for picking up objects?

Discussion in 'Scripting' started by Nsingh13, Jul 3, 2021.

  1. Nsingh13

    Nsingh13

    Joined:
    Dec 17, 2014
    Posts:
    36
    Hello,

    I am making a relatively simple game that has a system to pick up objects by clicking a button when you are near something. My first thought for implementing this is to use a trigger collider for each object because that is the most straightforward. So when I enter the trigger, the pickup button is activated which enables me to add the object to my inventory when I press it. One issue I noticed with the approach is that if two objects are close together then it sometimes glitches out on me (because the trigger colliders may overlap).

    So my question is if there is a better alternative to using OnTriggerEnter for my pickup system or any way I can modify it to make it work properly when two objects are close together?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    31,274
    You can use OnTrigger to add / remove given objects from something like a "Pickup Manager."

    This pickup manager would be in charge of maintaining an ongoing list of nearby things you can pick up, as well as notifying the UI that something could be picked up, and perhaps even doing the pickup step if you like.

    - If there are zero items available for picking up, no button.

    - If there is one item, hey, that's easy.

    - If there are two or more items, choose a heuristic for picking them up, such as "which item is closest to my player" or some other heuristic like "which item is worth more," or whatever you like.
     
  3. Nsingh13

    Nsingh13

    Joined:
    Dec 17, 2014
    Posts:
    36
    You're a freaking genius.

    My only question now is will OnTriggerEnter get both objects if say one of them is inside the trigger of another? It should call OnTriggerEnter for each object, right?
     
    Kurt-Dekker likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    31,274
    I'm guessing you could write a quick throwaway script and two-trigger setup and prove it in less time than it takes me to write this sentence back to you and then you will know for sure. :)

    In fact, I'd do that first... but you're probably already doing it as I type this, right?
     
  5. Nsingh13

    Nsingh13

    Joined:
    Dec 17, 2014
    Posts:
    36
    Haha, you're right! I'm going to work on it later though when I actually need to implement pickups :p. Will likely update the thread when I do in case anyone else had a similar question.
     
    Kurt-Dekker likes this.