Grab and Call Other Components with GetComponent<>

Classes, Variables and Functions

So far, we have made scripts and written some variables in those scripts. We have then used conditional logic to check and modify those variables. However, there are many instances when we'd want to use variables from another class/script.

Let's say we made a script in Unity and called it Character.

Then, we can make some variables inside of that script, such as health or goldAmount.

We could, if that class was set up correctly, read and write (look at and/or change) some of those variables using dot notation.

Dot notation allows us to drill into that class and access the variables and functions inside of it. The syntax is like so:

Character.health

Character.goldAmount

For variables to be accessible outside of the class they are made in, we need to give them the access modifier of public, before the type declaration, when declaring the variable:

//Pretend there's a class declaration up here...
{

public int health = 100;

public int goldAmount = 22;

//Pretend there's the Start() and Update() messages here.

}

Variables are not the only thing that can be attached to a class. We can also have class functions.

Functions are essentially commands that the class can do, that you set up. A character might have class functions such as:

  • Move

  • Jump

  • Shoot

  • Reload

  • Crouch

etc.

Functions sometimes need more information to do their job. Let's take a look at the examples above. Reload, for example, is a simple function that will always do the same thing; reset the bullets in our clip. Jump however is a little different. We may need to specify how much we want to jump. For this reason, functions are called with parenthesis after their name like so:

Character.Reload();

Character.Shoot();

Character.Jump(3.5f);

As you can see, these functions are all functions of the Character class, and they all require a parenthesis at the end of their calling, just in case they need some additional information passed to them for them to work. This additional required information is called the class parameter, and what you actually input are called the class arguments. As you can also see, the Character.Jump() function required an argument to work, so a number was given.

A quick note on the naming conventions of the terms function and variable. These are the most generic terms, but you may see other terms for these, such as:

For variables

  • Data members

  • Fields

  • Properties

  • Attributes

  • State

For functions

  • Methods

  • Procedures

  • Subroutines

  • Routines

  • Subprograms

  • Members

Unity specifically refers to these elements as 'fields' and 'members' in the debug console.

Other Components/Classes as Variables

Sometimes we want to either read/write the variables of another class, or call the function of another class. To bring it back to characters, we might want to make a character jump by using a Rigidbody component.

To gain access to the Rigidbody component attached to an object in a script, we can first make a variable, but the type will be the name of the component, instead of a data primitive like int, float, etc.

If we wanted to, we could make a variable to store a Rigidbody component in it:

public class Player : MonoBehaviour
{
    Rigidbody rb;
    
    //...

By doing this, we would be able to type rb. (rb followed by dot notation) to access all the variables and functions built into the Rigidbody component. However, this variable has been declared but not initialised; there's nothing inside this variable yet!

GetComponent<>

To assign something to this Rigidbody variable, we need use the GetComponent<> command. This is a function built into all Monobehaviour scripts (C# scripts made in Unity), which grabs components attached to the object that this script is attached to.

We need to call GetComponent<> in the Start() message, because components aren't actually added to objects until a game is running:

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

Here we can see that rb is being assigned to whatever is returned from the GetComponent<> function. We have an empty parenthesis here (no arguments), but we do have the name of the component in chevrons < >. This allows us to specify the type we are trying to get.

Using the Rigidbody Component at Runtime

Now we have access the Rigidbody component, we can use it while the game is running. Let's see if we can implement a jump.

In the Update() message, we can create an if() statement that checks whether the left mouse-button is clicked. The if() statement will look like this:

if (Input.GetMouseButtonDown(0))
        {
            
        }

Here, the condition of our if() statement is checking if the left mouse button is down using the Input class (also built-in to Monobehaviour scripts), specifically a function of the Input class called GetMouseButtonDown(). The argument to that function is the number 0 as this represents left-click. 1 would represent right-click.

We can then do something in the action section of the if() statement. Specifically, we are going to use one of the Rigidbody functions called AddForce().

AddForce() requires three arguments, separated by commas. These arguments are an amount of force along each axis.

rb.AddForce(0,0,0);

If we wanted to apply upwards force on left-click, it would look something like this:

if (Input.GetMouseButtonDown(0))
    {
    rb.AddForce(0,jumpForce,0);
    }

You should experiment now with some physics scripting. Can you make something akin to Flappy Bird or Angry Bird by launching physics objects into other objects?

Reference Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    Rigidbody rb;

    [SerializeField]
    float jumpForce = 100f;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            rb.AddForce(0,jumpForce,0);
        }
    }
}

Last updated