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
MediumLamp2 has no Light: make Space skip it, and show it is broken.
- In
Start(), replace theGetComponentline withhasBulb = TryGetComponent(out bulb);, with abool hasBulb;field. - When
hasBulbis false, color the lamp:GetComponent<Renderer>().material.color = Color.gray;. - In
Update(), switch the light only whenhasBulbis 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground