GetComponent<type>() throws error when null - how to avoid

Hey, need to do a pretty simple thing here:

if (this.transform.parent.GetComponent<PartInstallPoint>() != null){}

However, if the parent doesn’t have a component of PartInstallPoint this line throws an error. Is this possible to do using the GetComponent() method, or do I need to use GetComponents or the string method (GetComponent('PartInstallPoint")) to do a safe null check?

You are mistaken. GetComponent simply returns null if there is no such component.

Now, if parent is null, the above code will of course throw a null reference exception.

1 Like

The Error log can be hard to read sometimes because it just looks like something is null and a glance makes you assume it is the GetComponent or return from some method, but like Joe points out its probably the parent. Not a child == null parent. You set the parent to null if you want something dropped to the top of the hierarchy (world).

Do all of that in separate lines to get a more precise debug. Combine when it works.

1 Like

Doh - there clearly was a parent in the hierarchy, but after your comment, Joe, I took another look at the parent and the problem was obvious :p. I was creating and attaching it and my parent.GetC code was happening in the object’s Awake() method…where it didn’t have a parent yet. Fail! Moved it to the Start() and now it’s good, haha. I find I generally can’t find problems until I look like an idiot before others…sigh ;).

Publicly posting causes your IQ to go up ten points. Scientific fact. :slight_smile:

2 Likes

Hahaha, it’s so true.