Add a Component
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 46 of 85.
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 a warning in the Console instead, Can't add component 'Rigidbody'. Code that may run more than once asks whether the object already has the component before adding it.
Challenge
MediumSpace shakes the palm tree, and the coconut falls.
- In
Update(), onInput.GetKeyDown(KeyCode.Space), add a Rigidbody withgameObject.AddComponent<Rigidbody>(). - Add it only when the coconut has none:
!TryGetComponent(out Rigidbody rb). A second Space adds no second Rigidbody.
Press Play and press Space: the coconut drops to the sand. Then Check.
Try it yourself
using UnityEngine;
public class CoconutDrop : MonoBehaviour
{
void Update()
{
// Space: add a Rigidbody, if the coconut has none yet
}
}
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