Menu
CoddyTech

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 icon

Challenge

Medium

The 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics