Add a Component
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 32 of 67.
gameObject.AddComponent<T>() adds a new component of type T to the object while the game runs, and returns it so you can set it up on the next lines. It belongs to the GameObject, which a script reaches through gameObject. This campfire gives itself a warm orange light when the game starts:
void Start()
{
Light glow = gameObject.AddComponent<Light>();
glow.color = new Color(1f, 0.5f, 0f);
glow.intensity = 2f;
}A component added this way lasts while the game runs. Stop Play and the object is back to what the scene saved, with no Light. Your own scripts are components too: gameObject.AddComponent<Spinner>() adds a Spinner that starts running like any other script.
Most components can be added more than once, but some cannot: an object holds at most one Rigidbody, and asking for a second one gets an error in the Console instead. Code that may run more than once asks whether the object already has the component before adding it.
Challenge
MediumThe coconut hangs in the palm tree. Pressing Space shakes the tree: the coconut gets a Rigidbody, so gravity takes it and it falls to the sand.
- Before the first Space, the coconut hangs where it is.
- Space adds a Rigidbody only when the coconut has none yet, so later presses ask for nothing.
Press Play, press Space, then Check.
Try it yourself
using UnityEngine;
public class CoconutDrop : MonoBehaviour
{
void Update()
{
// Space: add a Rigidbody, if the coconut has none yet
}
}
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