Home > database >  How do I fix my pickup system in Unity 3D?
How do I fix my pickup system in Unity 3D?

Time:10-04

I'm trying to implement a very basic pickup system into my Unity game; when the player collides with an object, the object is destroyed. I followed a YouTube tutorial that showcased the code below, but it didn't work for me as my player just kept phasing through the object and it would still be there. I just wanted to know what was wrong with the code or which components I might need to tweak for this to work.

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

public class PickupObject : MonoBehaviour
{
    void OnTriggerEnter(Collision collider)
    {
        if (collider.gameObject.tag == "Player")
        {
            Destroy(gameObject);
        }
    }
}

CodePudding user response:

Check if you set isTrigger in the Collider of the PickUpObject in the scene to true. Because you use OnTriggerEnter and not OnCollisionEnter, the function only gets triggered when the collider is a trigger. If that is not the case, then add a Debug.Log() statement to your function to see if it gets called. Example:

void OnTriggerEnter(Collision collider)
{
    Debug.Log("function is called");
    if (collider.gameObject.tag == "Player")
    {
        Destroy(gameObject);
    }
}

Then you can check if the function was called in the console.

CodePudding user response:

Read the docs for OnTriggerEnter and look at call conditions:

Note: Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component.

Maybe you left IsTrigger field unchecked on your object with script. Or you have IsTrigger field true on your player (if so, uncheck). Or you don’t have rigidbody attached to your player object (if so, add).

  • Related