Missing Components
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 31 of 67.
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
MediumSpace switches the street lamps on and off, but Lamp2's bulb is broken: it has no Light, and pressing Space stops with MissingComponentException. Fix the script:
- Lamps that have a Light still switch on and off with Space.
- A lamp without a Light never touches it, so there is no error.
- When the game starts, a lamp without a Light colors its bulb
Color.gray, so players can see it is broken.
Press Play, then Space to see the error. Fix it, 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;
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch