Menu
CoddyTech

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 icon

Challenge

Medium

Space shakes the palm tree, and the coconut falls.

  1. In Update(), on Input.GetKeyDown(KeyCode.Space), add a Rigidbody with gameObject.AddComponent<Rigidbody>().
  2. 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

Practice on your own: Unity playground