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.

--

--

--

Game Developer focused in Unity with experience in Unreal Engine, Former Race Car Driver

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Not easy but worth it

AF Final Project (Fashion-Store) Progress

GXChain Progress Report June.13-June.19

Unity new Input System : Tips to create a “clean” Player Input System(Part XI)

Do you know how pod is created on Kubernetes?

Image: Pod Creation, Do you know how pod is created on Kubernetes?

How to Increase Efficiency With HubSpot Workflow APIs

Azure Data Factory Automation — Adding Log Analytics for Monitoring

Turbocharging Python with Command Line Tools

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
Zac Bogner

Zac Bogner

Game Developer focused in Unity with experience in Unreal Engine, Former Race Car Driver

More from Medium

Initializing A Git Repository in Unity

Setting Up Git

Doing basic unit testing in Unity/C#

Setting up GIT for Unity