OnTriggerEnter2D not working

Ok, so I am trying to get my Player to be able to pickup items that then disappear from the scene. I am able to do this by manually making the bool true but it won’t register on its own via collision detection. If I set the bool to true for multiple items, it doesnt matter where I am in the scene, they all disappear.

Here’s my code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ItemPickupItem : MonoBehaviour
{
    [SerializeField]
    private bool pickUpAllowed;

  
    // Update is called once per frame
    private void Update()
    {
        if (pickUpAllowed && Input.GetKeyDown(KeyCode.G))
            PickUp();
    }

    private void OnTriggerEnter2d(Collider2D other)
    {
        if (other.gameObject.name.Equals("Player"))
        {
            pickUpAllowed = true;
        }
    }
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.name.Equals("Player"))
        {
            pickUpAllowed = false;
        }
    }
    private void PickUp()
    {
        Destroy(gameObject);
    }
  
}

The Player has a box collider 2d (Not trigger) and a rigidbody.

The item has a box collider 2d (trigger) and a rigidbody as well (for physics).

Anyone have any insight to how I can fix this?

Firstly, whenever posting code snippets, always use code tags.

Using Debug.Log statements throughout your codes will give you a better insight of what is working and what is not
If it was me. I wouldn’t do it like that. I would compare using tags, so

if(other.gameObject.tag == "Player")
{
      // Do something...
}

Do you have any errors in the console?

As Johan points out above, if you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: Using code tags properly

Go check the docs for the OnTrigger function and make sure you are meeting all of the requirements to receive that callback. With Unity the answer is never just code; it has to be integrated correctly too.

And also as Johan suggested, use Debug.Log… a LOT. To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

EDIT: right away, even looking at your unformatted code, I see some very very very suspicious capitalization going on there. You need to type callback function names PRECISELY correct!!

Sorry, looks like the first part of the code snippet got inadvertently deleted. My apologies and it has now been fixed. There were no errors in the console. I adjusted using your suggestions and the outcome was the same with no Debug.Log entires in the console either.

The call backs have been verified to not be suspicious but to be correct. Also, adding in Debug.Log() did not help as it produced no console entries. I can however, as stated in the original post, confirm that at least part of the code is running as I can set the bool to true for any item and have it destory from the scene.

Really??? Are you SURE?

7229803--869962--wrong.png

Until you get it right, it won’t work.

2 Likes

Confirmed, all suffixes for 2D callbacks, methods etc are capital D so it should be “OnTriggerEnter2D”.

The “Enter” callback above won’t be called by Unity whereas the “Exit” callback will.

1 Like

Thank you for the help. Even after fixing the 2D callbacks, the code still does not detect via colliders. I still have to set the pickUpAllowed bool to true manually for the item to destroy. Distance and detection do not matter. Any thoughts?

Here is my updated code. All the debugs work but the Debug.Log(“key”) prints repeatedly as if the criterion are being met even when the player is nowhere close to the item.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ItemPickupItem : MonoBehaviour
{
    [SerializeField]
    private bool pickUpAllowed = false;


   
    // Update is called once per frame
    private void Update()
    {
        if ((pickUpAllowed = true) && Input.GetButtonDown("pickup"))
            PickUp();
            Debug.Log("key");
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player")
        {
            pickUpAllowed = true;
            Debug.Log("yes");
        }
    }
    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.tag != "Player")
        {
            pickUpAllowed = false;
            Debug.Log("Exit");
        }
    }
    private void PickUp()
    {
        Destroy(gameObject);
        Debug.Log("destroy");
    }
   
}

That’s because that line is outside of your if condition check. When you do not put { } as part of the if statement, then it will default to only be the next valid line.
So your code is basically becoming this:

if ((pickUpAllowed = true) && Input.GetButtonDown("pickup"))
{
            PickUp();
}
Debug.Log("key");

Try putting both lines inside { } so that they are both part of the if condition:

if ((pickUpAllowed = true) && Input.GetButtonDown("pickup"))
{
            PickUp();
           Debug.Log("key");
}
1 Like

Thank you! That fixed the debug issue. However, all items still destroy regardless of collision. Any idea why this would be happening? Another syntax thing?

NVM! I figured it out! thanks for all the help everyone!

1 Like