Using GetComponent in Unity

Andrea Zilio
3 min readMay 1, 2021

--

Get Component — the easy way to have scripts communicate with each other in Unity.

Adapted from photo by Thomas Griesbeck on Unsplash

Why use it?

Let’s say we want to update player stats such as player health or score in a UI object. Let’s assume we already have a player and a UI script. GetComponent will allow us to access the UI script from within the player script.

Setting up a variable

We first need to create a global variable in the script where we want to access the other script. Here it is the player script.

This variable will store the UI Manager script, so that we can access it easily from the player script.

Getting the component

Once the variable is created, we now need to find the script and get the component. Our UI Manager script is attached to the Canvas game object in Unity.

Once we know where to search, we can grab our UI Manager script and store it in the variable _uiManager. We do this in the void Start() method.

Here is what the code looks like:

So let’s have a look at the syntax. We ask the program to find the object “Canvas” of the type GameObject, then we tell it to get the component <script> called UI Manager.

var = GameObject.Find(“Name GameObject").GetComponent<script>();

If the component is not found, then null is returned. Thus it is good practice to check if the component is available and add an entry into the debug log if it is not.

We can now access the UIManager script from within the player script.

A warning

Photo by janilson furtado on Unsplash

It is important to notice that GetComponent is expensive. Doing so too often will have an impact on performance.

Enjoying the results

The two scripts can now communicate. I can, from within the player script update the UpdateScore function of the UIManager by passing the _score value.

And the Update Score allows me to display the new score in my text object called _scoreText.

So now the player can enjoy seeing their score. And all of this because GetComponent allows those two scripts to communicate.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Andrea Zilio
Andrea Zilio

Written by Andrea Zilio

Passionate Game Developer and Learning Expert. I love to create games and interactive experiences using Unity, Articulate, C#, JavaScript, PHP, HTML, CSS.

No responses yet

Write a response