Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Editor and Project Basics

GameObjects and Components

Understand GameObjects, components, tags, layers and the active state in Unity, and build objects in code with AddComponent, with runnable plain C# stand-ins.

Everything you see in a Unity scene is a GameObject, and everything a GameObject does is done by its components. This lesson digs into that pair: what a GameObject really contains, the most common built-in components, how to create objects in the editor and in code, and the other properties every GameObject carries: name, tag, layer, active state and static flags.

Because Unity cannot run on this page, the Unity scripts are read-only. The stand-ins in plain C# reproduce the component pattern so you can see how AddComponent and GetComponent work conceptually.

Anatomy of a GameObject

A GameObject has very little of its own:

  • a name (not unique; two objects can share it),
  • a Transform component (mandatory; position, rotation, scale and parent),
  • an active flag,
  • a tag and a layer,
  • a list of other components.

An empty GameObject (GameObject > Create Empty) is useful by itself: as a folder for grouping, as a spawn point, or as a pivot to rotate other objects around.

Common built-in components

Component What it does
Transform Position, rotation, scale, parent/child
MeshFilter + MeshRenderer Holds a mesh and draws it with a material
SpriteRenderer Draws a 2D image
Camera Renders the scene for the player
Light Lights the scene
Rigidbody / Rigidbody2D Physics movement
BoxCollider, SphereCollider, MeshCollider Shape used for collisions
AudioSource Plays sounds
Animator Plays animations
Your MonoBehaviour scripts Your game logic

Think of a cube from the menu: it is a GameObject with Transform, MeshFilter, MeshRenderer and BoxCollider. Nothing special; just four components in one container. Remove the MeshRenderer and the cube becomes invisible but still solid.

Adding and removing components

In the Inspector, click Add Component and search. You can also add one in code:

C#
using UnityEngine;

public class Bootstrap : MonoBehaviour
{
    void Start()
    {
        var body = gameObject.AddComponent<Rigidbody>();
        body.mass = 2f;

        var audio = gameObject.AddComponent<AudioSource>();
        audio.playOnAwake = false;
    }
}

gameObject is the GameObject this script is attached to; AddComponent<T>() returns the new component, so you can configure it immediately. To remove a component call Destroy(component).

Your own scripts can declare dependencies with an attribute, which Unity enforces for you:

C#
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Floater : MonoBehaviour
{
    void FixedUpdate()
    {
        GetComponent<Rigidbody>().AddForce(Vector3.up * 5f);
    }
}

[RequireComponent] adds a Rigidbody automatically when you attach Floater and blocks you from removing it while Floater is there.

Components in plain C#: a stand-in

Here is the same machinery in ordinary C#. A GameObjectLike stores components in a list and offers AddComponent and GetComponent using generics, just as Unity's API does. Note that GetComponent returns null when nothing matches.

C# AddComponent and GetComponent (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In real Unity, calling a method on a null result throws a NullReferenceException, so scripts check for null or use TryGetComponent, which you will meet in Finding and Referencing Components.

Name, tag and layer

  • Name: what the Hierarchy shows. GameObject.Find("Name") searches by it, but that is slow and fragile; prefer direct references.
  • Tag: a string label such as Player or Enemy. Built-in tags are Untagged, Respawn, Finish, EditorOnly, MainCamera, Player and GameController. Add your own in Tags and Layers. Compare with gameObject.CompareTag("Enemy"), which is faster than == and warns about unknown tags.
  • Layer: a number from 0 to 31 with a name. Layers control what the camera renders (culling mask), what lights hit, and which physics objects collide (the Layer Collision Matrix). You will use layers heavily in raycasting.

A GameObject has exactly one tag and one layer. Use a layer for "who collides with whom" and a tag for "what is this thing" in game logic.

Active and inactive objects

The checkbox at the top of the Inspector sets gameObject.activeSelf. An inactive object is invisible, receives no Update calls, plays no physics, and its children are inactive too (activeInHierarchy reports the effective state). Disabling a single component, by contrast, only turns off that component (a disabled MeshRenderer hides the object but physics still works).

C#
// read-only Unity script
gameObject.SetActive(false);          // the whole object stops
GetComponent<Collider>().enabled = false;   // only the collider stops

A common pitfall: a script on an inactive object cannot start a coroutine, and Find does not return inactive objects by default.

Static flags

Marking an object Static (the checkbox next to the name) tells Unity it never moves. Static objects can be batched (drawn together), baked into lightmaps, included in navigation meshes, and occlusion culled. Never move a static object at run time; use it for floors, walls and scenery.

Creating GameObjects in code

C#
// read-only Unity script
using UnityEngine;

public class Spawner : MonoBehaviour
{
    void Start()
    {
        var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        cube.name = "Runtime Cube";
        cube.transform.position = new Vector3(0, 2, 0);

        var empty = new GameObject("Marker");     // empty object
        empty.transform.SetParent(transform);     // make it a child
    }
}

CreatePrimitive builds a ready object with a mesh, renderer and collider. new GameObject("name") makes an empty one and you add the components you need.

Parenting and organizing

Children inherit the parent's transform. Use empty parents to organize: an Enemies group, a Level group, a Managers group. Be careful about scale on parents: a parent with scale (2, 1, 1) and a rotated child gives skewed results. Keep parent scale at (1, 1, 1) when you can.

Here is the idea of tags and layers as a stand-in: filtering objects by a tag, as game logic does constantly.

C# Tags and filtering (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The bit-shift at the end is exactly how Unity layer masks work: bit number N stands for layer N. That is why the number for layer 9 is 512.

Common mistakes

  • Looking for a component on the wrong object (use the Inspector to check where the script is attached).
  • Using GameObject.Find every frame; store the reference once.
  • Misspelling a tag; use CompareTag and define your tags in the editor.
  • Moving a static object.
  • Disabling the GameObject that holds the script that should re-enable it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which component does every GameObject have?

    Transform is mandatory and cannot be removed.
  2. 2. What does [RequireComponent(typeof(Rigidbody))] do?

    The attribute declares a dependency that the editor enforces.
  3. 3. What is the effect of gameObject.SetActive(false)?

    An inactive object receives no Update calls, is not rendered and does not take part in physics.
  4. 4. Which is the recommended way to compare tags?

    CompareTag avoids allocating a string and reports an error if the tag does not exist.

Summary

  • A GameObject is a container: name, Transform, tag, layer, active flag and components.
  • Behavior comes from components; add them in the Inspector or with AddComponent<T>().
  • [RequireComponent] documents and enforces dependencies.
  • Tags name kinds of objects; layers drive physics and rendering filters; layer masks are bit fields.
  • Mark unmoving scenery as Static; deactivating an object stops all its components and children.

Next: Transforms and Coordinate Systems