Mastering GetComponent in Unity

Objective: (For an Internal Project […] our Turret Projectile needs to communicate with the PlayerController prefab object).

GetComponent allows us to get class objects of its type and components for reference in Unity.

In order for GetComponent to work, we will need to identify the object existence.

For example, we can reference the player game object by the name “PlayerController” and check if the player is null, and declare a return type shorthand to not execute the command.

Sometimes a wrong data type can be inserted resulting in a Null Reference Exception error.

Below is the error saying that the object is not the correct type.

Additionally, when the PlayerController becomes null, if not assigned or destroyed and not reloaded into data, a null reference exception will appear.

This happens because the Turret Projectile class component is trying to get reference to PlayerController that doesn’t exist.

Assigning the correct data type, the error for wrong component convert will go away.

The appropriate GameObject assigned will not throw a missing reference exception.

A best practice for GetComponent is to Null Check to ensure receiving of data we want to achieve within our applications.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store