1
\$\begingroup\$

I have this GameObject with the tag coin I am trying to destroy when the player collides with it using this code located in a player script attached to the player

    public void OnCollisionEnter(Collision col){
        var hit = col.gameObject;
        if(hit.tag == "Coin"){
            Destroy(hit.gameObject);
        }
    }

However upon collision nothing is happening

\$\endgroup\$

3 Answers 3

2
\$\begingroup\$

First you must check:

  1. collider => IsTrigger =>false
  2. Rigidbody => IsKinematic =>false
  3. you mentioned 3d so check their gameObjects z position
  4. finally you check your tag name into corresponding to their gameobject
\$\endgroup\$
1
\$\begingroup\$

I figured out the issue the problem was in order to use OnCollisionEnter at least one of the objects must have a rigidbody component attached

\$\endgroup\$
0
\$\begingroup\$

Few things you have to keep in mind.

  • Rigidbody must attached to either Gameobject
  • Make sure that your script attached to the GameObject is not isTrigger checked.
  • Verify if the OnCollisionEnter is being executed, by breakpoints or logs.
  • Make sure the tag of other GameObject (col.gameObject)
  • And you don't need to destroy hit.gameObject as hit is already a GameObject.

You can do it like

void OnCollisionEnter(Collision col){

    var hit = col.gameObject;

    Debug.Log("In collision enter");

    if(hit.tag == "Coin"){
        Debug.Log("In destroy check");
        Destroy(hit);
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .