How to correctly handle NullReferenceError when using GetComponent?

I am trying to use GetComponent, however, I get NullReferenceError as sometimes it does not find the component necessary.

So how do I handle the error other than try/catch block, maybe there is some better way to check if some object has component?

I have tried using something like:

TestComponent test = object.GetComponent<TestComponent>();

If (test != null) ...

However, it still throws exception.

EDIT:
The issue is gone after updating Unity.

The part that you said you tried using should be sufficient, unless of course ‘object’ is null. That’s how I ensure a component is there.

I usually do;

var component = object.GetComponent<mycomponent>();

if(component == null)
   return;

and that works for me.

Yep, if object is null, then you’ll get an error. But otherwise, that is how I would check it. I’d probably have an if/else to handle both cases, but otherwise, it should be fine.

The object is not null but test is null.
No idea why I keep getting the error.

If you keep getting the error, perhaps something is else isn’t right - not sure how to comment. Can you post the script and indicate where the error occurs? :slight_smile:

It is in the post, however, I updated Unity and the error is gone. Not sure what it was. Edited the first post just in case.

Fair enough. Glad it’s solved.