Search Unity

Collision detection error

Discussion in 'Scripting' started by robeng, Feb 12, 2018.

  1. robeng

    robeng

    Joined:
    Jun 16, 2016
    Posts:
    2
    Hi! I have a player object and an Item object. My player object has a script that should delete my item object upon collision. My item object has a script with an id number. I want to use that ID number to identify my Item object. Here is the code for the player that handles the collision:

    Code (CSharp):
    1. private void OnCollisionEnter(Collision collision)
    2.     {
    3.         if (collision.gameObject.GetComponent<Item>().id == 999)
    4.         {
    5.             Debug.Log("HIT");
    6.         }
    7.     }
    When running this i get this error in the console:

    I don't really understand. Any help appreciated!
    Thanks in advance!
     
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    the null ref tells me it does not find the Item script.

    put the collision detection on the item it's self. and check to see if the thing that hit the item is the player

    Code was free handed, sorry for any typo's
    Code (CSharp):
    1. private void OnCollisionEnter(Collision collision)
    2.     {
    3.         if (collision.transform.gameobject.tag == "Player")
    4.         {
    5.             Debug.Log("HIT by the Player");
    6.         }
    7.     }
     
  3. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Another option/consideration in general, is to make sure you have the correct game object :
    Code (csharp):
    1. Item theItem = collision.gameObject.GetComponent<Item>();
    2. if(theItem != null) {
    3.    // now we know it's there / was on the game object with which we had a collision.
    4.   }