Menu
CoddyTech

Missing Components

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 45 of 85.

When the component you ask for is not on the object, GetComponent does not stop you. In the Editor it hands back a stand-in that compares equal to null, and Unity throws the first time your code uses it. This ball should hop when Space is pressed, but nobody gave it a Rigidbody:

Rigidbody rb;

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

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.AddForce(Vector3.up * 300f);
    }
}

Space prints MissingComponentException: There is no 'Rigidbody' attached to the "Ball" game object, but a script is trying to access it. The message names the missing type and the object. Either add the component in the Inspector or, when the object may lack it on purpose, ask first. TryGetComponent(out rb) returns true and fills rb when the component is there, and returns false without an error when it is not (out lets the method hand a value back through the variable):

bool canHop;

void Start()
{
    canHop = TryGetComponent(out rb);
}

Update() then pushes the ball only if (canHop). Outside the Editor, in a built game, GetComponent returns a plain null instead, so the same mistake shows up there as a NullReferenceException.

challenge icon

Challenge

Medium

Lamp2 has no Light: make Space skip it, and show it is broken.

  1. In Start(), replace the GetComponent line with hasBulb = TryGetComponent(out bulb);, with a bool hasBulb; field.
  2. When hasBulb is false, color the lamp: GetComponent<Renderer>().material.color = Color.gray;.
  3. In Update(), switch the light only when hasBulb is true.

Press Play and press Space: the good lamps switch, with no error. Then Check.

Try it yourself

using UnityEngine;

public class LampSwitch : MonoBehaviour
{
    Light bulb;

    void Start()
    {
        bulb = GetComponent<Light>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            bulb.enabled = !bulb.enabled;
        }
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground