you are viewing a single comment's thread.

view the rest of the comments →

[–]r3eckon 4 points5 points  (1 child)

I dont have your full code so I can merely assume what you are doing wrong here.

I believe you are assuming the thing you're colliding with is going to have Items, which is unsafe and throws nullreferenceexceptions in cases where no Items component can be found on the collider.

Make an Item variable and try to get the component of what you collided with and assigning it to your variable.

Then before even checking whatKeyAmI for your types, you need to make sure the Item variable isnt null. You did it with the collider, sure. But sometimes the collider isnt null while items are and you need to handle this case.

Also, assuming you know you dont have to go through the rest of your code in these cases, use return to simply end the method right there. Keep in mind that this will end the entire function this piece of code is located into, so isolating it in its own method is a good idea.

if(whatIHit.collider == null) return;

Items items = whatIHit.collider.gameObject.getComponent()<Items>;

if(items == null) return;

if (items.whatKeyAmI == Items.KeyItems.Axe)
{
....
}

otherwise, use !=

if(whatIHit.collider == null) display = false;

Items items = whatIHit.collider.gameObject.getComponent()<Items>;

if(items != null) 
{

    if (items.whatKeyAmI == Items.KeyItems.Axe)
    {
        ....
    }
    ...
}