Lesson 1 - GameObjects and the Component Model

What a GameObject actually is (a named container with a Transform), why every capability - drawing, falling, colliding, running your code - is a component you attach, and the difference between switching an object off and destroying it.

Subject: Unity Game Engine · 61 slides · code lesson

Open the interactive version of this deck · Homework for this lesson

What this lesson covers

The lesson, slide by slide

1. GameObjects and the Component Model

Title

Unity - Lesson 1

A cube is not a kind of object. It is an empty container with four things bolted on.

2. What you will be able to do

Objectives

This lesson exists because of one diagnostic result: you got the GameObject questions right, and marked yourself unsure on all of them. That is a sign of a model that is nearly there.

  1. Say what a GameObject is without using the word 'object' - and name the one component every single one has
  2. Predict from the Inspector alone whether a cube will fall, be drawn, or be hit
  3. Explain why a script sitting in the Assets folder does nothing
  4. Choose correctly between SetActive(false), enabled = false and Destroy()
  5. Build a scene where each of those claims is printed to the Console by your own code

3. Before we start: what do you already believe?

Warm-up

Answer from memory. Being wrong here costs nothing and makes the next twenty minutes stick.

Discussion prompt

You drag a Cube into an empty scene. List everything you think that cube can now do, and next to each one write what makes it able to do that.

Hint: There are exactly four things attached to a fresh cube. Two of them are about being seen.

Answer:

A fresh cube can: be positioned (Transform), hold a shape (Mesh Filter), be drawn (Mesh Renderer), and be touched by contact tests (Box Collider).

It cannot fall, cannot be clicked, cannot run any code, and does not know it is a cube. Everything on that second list is a component you have not added yet.

4. What a GameObject actually is

Section

Part 1

5. A GameObject is a container, not a thing

Concept

Figure (svg): A GameObject drawn as a board labelled Cube, with four component cards attached: Transform, Mesh Filter, Mesh Renderer, Box Collider

Take the cards away and the board is still a GameObject. It just does nothing.

A GameObject has exactly two properties of its own: a name and a list of components. That is the whole definition.

GameObject — A named container that holds components. It has no behaviour of its own - every capability it appears to have comes from something attached to it.

Unity Manual - GameObjects GameObjects

6. Think of a pegboard, not a species

Intuition

A pegboard on a wall does nothing. Hang a hook on it and it holds a coat; hang a shelf and it holds a plant. The board never changed - the things on it did.

Unity has one kind of GameObject. A Camera, a Light, a Player and a Cube are the same type of container with different components hanging off them.

This is why there is no Cube class to inherit from, and why 'what type of GameObject is it?' is not a question Unity can answer. It only knows what is attached.

7. Predict: the empty GameObject

Prediction

GameObject > Create Empty makes an object with nothing on it.

Predict first

How many components does a brand-new empty GameObject have?

  • Zero - it is empty
  • One
  • Two
  • It depends on the template

Correct: One - the Transform.

Try it: create an empty object and look for the minus button on the Transform. There isn't one.

Why: Every GameObject has a Transform, always, and Unity will not let you remove it. An object with no position, rotation or scale would have no place in the scene, so 'empty' means 'empty apart from the one component that cannot be optional'.

8. The Transform is not optional

Concept

Position, rotation and scale live on the Transform component. Every GameObject has exactly one, and it is the only component you cannot remove.

The Transform is also what makes parenting work - a child's position is measured from its parent. Lesson 6 is entirely about that.

questionthe component that answers it
Where is it?Transform
What shape is it?Mesh Filter
Should it be drawn?Mesh Renderer
Can it be touched?Collider
Does it fall?Rigidbody
Does it run my code?your MonoBehaviour script

9. Components are capabilities you bolt on

Concept

Transform
Where it is. Always present.
Renderer
Draws it. No Renderer, invisible.
Collider
A shape for contact tests. Not physics.
Rigidbody
Hands the position to the physics solver.

Add a Rigidbody and the object falls. Remove the Mesh Renderer and it vanishes but still collides. Each capability is independent, and each is a row in the Inspector.

Unity Manual - Introduction to components Introduction to components

10. Match the symptom to the missing component

Matching

Each of these is a real thing a beginner says. Match it to what is actually missing.

Match the pairs

Drag each complaint onto the component that would fix it.

  • a. I can see it but it never falls
  • b. It falls straight through the floor
  • c. It is in the Hierarchy but I cannot see it
  • d. My script never prints anything
  • r1. Rigidbody (on the falling object)
  • r2. Collider (on the floor)
  • r3. Mesh Renderer
  • r4. the script itself, attached to an object

Why: Every one of these is a missing component, not a broken setting. That is the diagnostic habit worth building: when something does not happen in Unity, the first question is 'what is attached?', not 'what did I type wrong?'.

11. Reading a cube's Inspector, in code

Worked example

GetComponents<Component>() returns the honest answer to 'what is this made of?'. Here it is on a plain cube.

using UnityEngine;

public class ComponentReport : MonoBehaviour
{
    void Start()
    {
        Component[] parts = GetComponents<Component>();
        Debug.Log($"{name} has {parts.Length} components");
        foreach (Component part in parts)
            Debug.Log("  " + part.GetType().Name);
    }
}

Attach it to a plain cube and press Play

Why: Nothing runs until the script is a component on an object - that is the whole point of the next section.

printed linewhat it iscould you remove it?
Transformposition, rotation, scaleno - never
MeshFilterwhich mesh: the cube shapeyes, it goes invisible
MeshRendererdraws the mesh with a materialyes, it goes invisible
BoxColliderthe shape used for contact testsyes, things pass through it
ComponentReportyour script - itself a componentyes, that is the checkbox

Five lines, not four: your script is in the list. It is not 'the object' - it is one more part bolted on beside the others.

12. Why is your own script in that list?

Explain it to yourself

Discussion prompt

The report printed five components on a cube that visibly has four things in the Inspector. Explain, in your own words, why ComponentReport appears in its own report.

Hint: What does the word MonoBehaviour inherit from?

Answer:

Because MonoBehaviour is a component. Your class inherits from MonoBehaviour, which inherits from Behaviour, which inherits from Component.

So a script is not something a GameObject has in a special way - it is attached in exactly the same way a Collider is, appears in the same list, and has the same enabled checkbox.

13. Three kinds of thing beginners mix up

Sorting

Unity has objects in a scene, components on those objects, and assets in the Project window. They are not interchangeable.

Sort into buckets

Sort each one.

GameObject in the scene
The Cube in your Hierarchy; Main Camera
Component on an object
Rigidbody; Transform
Asset in the Project
Coin.prefab in the Project window; Your PlayerMove.cs file in Assets
scene
It appears in the Hierarchy, exists only while this scene is open, and is a container with components on it.
comp
It appears as a row in the Inspector of some object. It cannot exist on its own - it is always attached to something.
asset
It is a file in the Project window. It exists on disk, survives closing the scene, and is not in the game until something uses it.

14. Trap: 'a Cube is a kind of GameObject'

Trap

The trap

The mental model: GameObject is a base class, Cube extends it, and my Coin script extends Cube.

// The way it feels like it should work
public class Coin : Cube          // <- there is no Cube class
{
    void Start() { ... }
}
beliefconsequence
Cube is a typeyou look for a Cube class to inherit from
My script IS the objectyou expect this to be the whole cube
Objects differ by typeyou cannot explain how a Camera and a Cube are related

The fix

There is one GameObject type. 'Cube' is a name plus a Mesh Filter that happens to hold the cube mesh.

// The way it really works
public class Coin : MonoBehaviour   // a COMPONENT you attach
{
    void Start()
    {
        // 'this'       -> the Coin component
        // 'gameObject' -> the container it is attached to
    }
}
factconsequence
One GameObject typeyou compose with components instead of inheriting
Your script rides on the objectthis and gameObject are two different things
Objects differ by what is attacheda Camera is a GameObject with a Camera component

15. Find the bug: this compiles and does the wrong thing

Error analysis

Every line here is legal C#. One of them is a category error.

Annotate

  • Correct: your class extends MonoBehaviour, so it is a component that can be attached.
  • The bug. this is the Coin COMPONENT. Destroying it removes the script and leaves the coin sitting there, visible and solid, forever. You meant Destroy(gameObject).
  • This line still runs. Destroy is deferred to the end of the frame - lesson 5 measures that gap.

this versus gameObject is the single most useful distinction in this lesson. One is the part; the other is the whole.

16. Your script is a component like any other

Concept

A MonoBehaviour has the same two switches every component has: the object it is on can be inactive, and the component itself can be disabled.

// three different ways of "turning it off"
GetComponent<Coin>().enabled = false;   // this script stops; the object is fine
gameObject.SetActive(false);            // the whole object stops
Destroy(gameObject);                    // the whole object is removed
callwhat stopswhat survives
enabled = falsethat one script's Updateeverything else on the object
SetActive(false)the whole objectthe object itself, in the scene
Destroy(gameObject)everythingnothing

17. Two of these are true

Two truths and a lie

One statement below is false. Rule it out and say what rules it out.

Eliminate the wrong options

Which claim about components is false?

  • A. A GameObject can have two of the same component (two Audio Sources, say).
  • B. A component can exist without being attached to a GameObject.
  • C. Unticking a component's checkbox stops its Update without affecting the object.

Survives elimination: B

Why: B is the false one, and it is the useful falsehood: a component is defined by the object it is attached to, which is why new Rigidbody() is refused and AddComponent<Rigidbody>() is the way in. A and C are both true - duplicates are allowed unless the script says [DisallowMultipleComponent], and the checkbox is per component.

18. Physics is opt-in

Section

Part 2

19. Nothing falls until you say so

Concept

Unity does not apply gravity to objects. It applies gravity to Rigidbodies. An object without one is not 'held up' by anything - it was never being simulated in the first place.

Rigidbody — The component that hands an object's position over to the physics solver. Without it, an object's position is whatever your code or the Inspector last set.

Unity Manual - Introduction to components components

20. Predict: two identical cubes

Prediction

Two cubes, same size, same position, same material. One has a Rigidbody; the other does not. You press Play.

Predict first

What happens to the cube WITHOUT the Rigidbody?

  • It falls more slowly
  • It falls, then stops at the floor
  • It does not move at all
  • It falls only if something touches it

Correct: It does not move at all - not slowly, not eventually. Nothing is simulating it.

Why: This is the difference between 'gravity is switched off for this object' and 'this object is not part of the physics simulation'. The second is the true one. It has a Collider, so other things can be stopped by it, but nothing will ever move it.

21. Adding the capability mid-play

Worked example

AddComponent<T>() is the Add Component button, in code. Watch the moment a cube gains physics.

public class AddComponentAtRuntime : MonoBehaviour
{
    public GameObject target;
    public float addAfterSeconds = 3f;
    bool added;

    void Update()
    {
        if (added || Time.timeSinceLevelLoad < addAfterSeconds) return;
        added = true;
        Rigidbody body = target.AddComponent<Rigidbody>();
        body.mass = 1f;
    }
}

Nothing about the cube changed except its component list

Why: It has the same mesh, the same material, the same position. One row appeared in the Inspector and it started falling.

timecomponents on the cubeis it moving?
0.0sTransform, MeshFilter, MeshRenderer, BoxColliderno
2.9ssame fourno
3.0sthe four, plus Rigidbodyyes - it starts to fall
3.5sthe fiveyes, accelerating at 9.81 m/s squared

22. Which component, not which value

Discrimination

For each goal, pick the component you would add. Do not think about settings yet.

Sort into buckets

Sort each goal under the component that provides it.

Needs a Rigidbody
A crate that falls and tumbles
Needs a Collider only
A wall that stops the player; A coin that spins and can be collected; An invisible boundary the player cannot cross
rb
The object itself has to be moved by the simulation - it falls, it is pushed, it tumbles. Only then does it need a Rigidbody.
col
The object only needs to be a SHAPE that other things test against. Walls, floors, boundaries and trigger zones are all static colliders, and giving them a Rigidbody usually breaks them.

23. Trap: 'it has a Collider, so it has physics'

Trap

The trap

The cube has a Box Collider. Physics is clearly involved. So it should fall.

// "why isn't my cube falling? it has a collider!"
void Start()
{
    GetComponent<Rigidbody>().mass = 2f;   // NullReferenceException
}

GetComponent<Rigidbody>() returned null, because there is no Rigidbody. The next . throws.

The fix

A Collider is a shape. A Rigidbody is being simulated. They are independent, and most objects in a game want the shape without the simulation.

void Start()
{
    if (TryGetComponent(out Rigidbody body))
        body.mass = 2f;
    else
        Debug.Log("no Rigidbody here - this object is not simulated");
}
what it haswhat it can do
Collider onlystop things, be a trigger; never moves on its own
Rigidbody onlyfall and be pushed; passes through everything
Bothfalls AND is stopped - a crate

24. Fill in the capability table

Comparison

Three components, three questions. Fill the blanks from what you have seen so far.

Comparison matrix

Is it drawn?Can it be hit?Does it move on its own?
Mesh Renderer onlyyesnono
Collider onlynoyesno
Rigidbody + Collideronly with a Rendereryesyes

The middle row is the one worth staring at: a Collider with no Renderer is a perfectly normal object. Every trigger zone in every game you have played is exactly that.

25. GetComponent asks; it never creates

Concept

GetComponent<T>() searches what is already attached and returns null if there is no T. Asking for a Rigidbody does not conjure one.

Rigidbody body = GetComponent<Rigidbody>();   // null if there isn't one
if (body == null)
    body = gameObject.AddComponent<Rigidbody>();   // this is the call that creates
callsearches?creates?returns
GetComponent<T>()yesnothe component or null
AddComponent<T>()noyesthe new component
new T()norefused for componentsan error in the Console

Unity Scripting API - GameObject.GetComponent GetComponent

26. Complete the safe lookup

Fill the middle

Fill the blanks so this reads a Rigidbody's mass without ever throwing.

Fill in the blanks

void Start()
GetComponent}<Rigidbody>();
if (body != null)
Debug.Log(body.mass);
else
Debug.Log("not simulated");
}

Why: GetComponent searches and may return null, so the null check is not defensive noise - it is the actual API contract. Unity overloads == for components so a destroyed or missing component compares equal to null, which is what makes this readable.

27. Off, disabled, or gone

Section

Part 3

28. Three different switches

Concept

Figure (svg): Three switches diagram: object active, component enabled, and destroyed, showing what survives each

Three different switches. Only one of them cannot be undone.

These are not three ways of saying the same thing. They differ in what stops, what survives, and whether you can undo it.

Unity Scripting API - GameObject.SetActive GameObject.SetActive

29. A light switch is not a demolition

Intuition

Switching a room's light off leaves the room, the furniture and the address exactly where they were. You can switch it back on.

Demolishing the building leaves nothing. The address is not 'off' - it is invalid, and so is every piece of paper pointing at it.

SetActive(false) is the switch. Destroy() is the demolition. The reason to care is that after a Destroy, every reference anyone kept to that object is now dead - and using one is the most common runtime error in Unity.

30. Predict: after SetActive(false)

Prediction

A cube with a script whose Update prints once a second. At t = 2s something calls SetActive(false) on it.

Predict first

What happens to the printing, and to the reference you were holding?

  • Printing stops, reference goes null
  • Printing stops, reference stays valid
  • Printing continues, reference stays valid
  • Printing stops and OnDestroy runs

Correct: Printing stops, and the reference stays valid.

Why: An inactive GameObject runs no Update, draws nothing and collides with nothing - but it is still in the scene with all its components and values intact, so any reference to it still points at something real. OnDisable runs; OnDestroy does not, because nothing was destroyed.

31. The two-cube experiment, traced

Worked example

This is the lab script for lesson 1. Two identical cubes: one is switched off, one is destroyed, and both are polled every second afterwards.

void Update()
{
    if (!acted && Time.timeSinceLevelLoad >= 2f)
    {
        acted = true;
        toDeactivate.SetActive(false);
        Destroy(toDestroy);
    }
    if (acted && Time.timeSinceLevelLoad >= nextReport)
    {
        nextReport += 1f;
        Debug.Log($"deactivated alive: {toDeactivate != null}");
        Debug.Log($"destroyed alive:   {toDestroy != null}");
    }
}

Poll both references once a second

Why: The question obj != null is how you ask 'does this still exist?'. Unity overloads == for objects precisely so this reads naturally.

timedeactivated: reference alive?deactivated: running?destroyed: reference alive?
1s (before)truetruetrue
2s (the calls)truefalsetrue - until end of frame
3struefalsefalse
4struefalsefalse
5struefalsefalse

The deactivated cube never leaves the table. It is off, not gone - and SetActive(true) brings it back mid-run.

32. What stays the same as you switch things off?

Invariant

Step through the four states and watch which row never changes.

Step through it

One column here is constant across all four frames. Which, and why?

  1. Everything on.
  2. enabled = false on one script.
  3. SetActive(false) on the object.
  4. Destroy(gameObject).

'Reference still valid' stays true for the first three frames. Only destruction invalidates it - which is exactly why mixing up the third and fourth states produces a bug that appears one frame later.

33. Trap: SetActive(false) as a way to delete

Trap

The trap

The coin has been collected, so switch it off. Same thing as deleting it, and easy to undo.

void Collect()
{
    gameObject.SetActive(false);
    score += 1;
}
  • After 500 coins, 500 inactive GameObjects are still in the scene
  • GameObject.Find skips them, so debugging gets confusing
  • Every one still holds its mesh, material and components in memory
  • Saving the scene saves all 500

The fix

Decide by intent. Coming back? switch it off. Never coming back? destroy it.

void Collect()
{
    score += 1;
    Destroy(gameObject);     // gone at the end of this frame
}

void Respawn()               // the case where SetActive really is right
{
    checkpointFlag.SetActive(true);
}
intentthe callundo?
collected for goodDestroy(gameObject)no - Instantiate a new one
hidden until laterSetActive(false)yes - SetActive(true)
pooled for reuseSetActive(false), deliberatelyyes - that is the point

There is a third option once you know it: object pooling - deactivate instead of destroy specifically because you will reuse the object. That is a deliberate choice, not a synonym.

Unity Scripting API - Object.Destroy Object.Destroy

34. Pick the right call for this one job

Elimination

A pickup should disappear when collected, and reappear at the start of the next round.

Eliminate the wrong options

Which is the right call when the player collects it?

  • A. gameObject.SetActive(false)
  • B. Destroy(gameObject)
  • C. Destroy(this)
  • D. GetComponent<Renderer>().enabled = false

Survives elimination: A

Why: Reuse is the deciding fact. Because the pickup comes back next round, deactivating is right and cheap - the object keeps its position and its wiring, and SetActive(true) restores it. Choice D is worth noticing: hiding something is not the same as switching it off, and a hidden-but-active collider is a real bug you will meet.

35. Order the callbacks

Ranking

You call SetActive(false) on an object at t = 2s, then stop Play mode at t = 5s. Put the callbacks in the order Unity fires them.

Put in order

Earliest first.

  1. Awake
  2. Start
  3. Update (running each frame)
  4. OnDisable (at t = 2s)
  5. OnDestroy (when Play stops)

Why: OnDisable runs when the object is deactivated, and again on the way to destruction - so OnDestroy is never the first goodbye. That ordering is why subscribe-in-OnEnable and unsubscribe-in-OnDisable is the standard pairing: it survives an object being switched off and on again, which OnDestroy would not.

36. activeSelf and activeInHierarchy

Concept

An object can be switched on and still not running, because a parent above it is switched off. Unity gives you both answers.

// parent is inactive; child was never touched
child.activeSelf          // true  - the child's own switch is on
child.activeInHierarchy   // false - but nothing above it is running, so neither is it
propertyaskstypical use
activeSelfis MY switch on?restoring an object to how you found it
activeInHierarchyam I actually running?the one you almost always want

37. Break this claim

Counterexample

Discussion prompt

A classmate says: 'If activeSelf is true, the object is running.' Give a concrete two-object scene where that is false.

Hint: You only need a parent and a child.

Answer:

Parent Hud with child ScoreLabel. Call Hud.SetActive(false).

ScoreLabel.activeSelf is still true - nobody touched its switch. ScoreLabel.activeInHierarchy is false, and its Update does not run.

This is the bug behind 'my script stopped working and I never disabled it'. Something above it in the Hierarchy did.

38. Build it in Unity

Section

Part 4

39. What you are about to build

Concept

A scene that prints its own component model to the Console. Five cubes, three scripts, and every claim in this deck checked out loud.

ComponentReport
Prints the real component list of whatever it is on.
ActiveVsDestroy
Switches one cube off, destroys another, polls both.
AddComponentAtRuntime
Gives a cube a Rigidbody three seconds in.

Files: unity-labs/Assets/NaruhodoLabs/Lesson01_GameObjects/. Full instructions in that folder's SETUP.md.

40. Plan it before you open Unity

Step zero

Discussion prompt

Before touching the editor: what is the smallest scene that proves 'SetActive(false) is not Destroy'? Name the objects and what each one is for.

Hint: You need two things that are identical apart from what happens to them, and something to do the doing.

Answer:

  • Two identical cubes - identical so the only difference is the treatment
  • One empty GameObject holding the script that acts on both - so neither cube can be accused of doing it to itself
  • A clock - a time check, so the change happens while you are watching
  • A report - polling both references afterwards, or you are just guessing from the Game view

That is the shape of every experiment in this course: two things, one difference, one observer.

41. Step 1: the project and the first cube

Worked example

Unity Hub, new project, 3D. Then build the object and read it before adding anything.

  1. GameObject > 3D Object > Cube, rename it PlainCube, Position (-3, 0.5, 0)
  2. In the Inspector, write down every row you see - there will be four
  3. Add Component > New Script, name it ComponentReport
  4. Press Play and read the Console
Inspector rowwhat it doesin the printed list?
Transformposition, rotation, scaleyes
Mesh Filterholds the cube meshyes
Mesh Rendererdraws ityes
Box Collidershape for contact testsyes
Component Reportyour scriptyes - it counts itself

42. Step 2: the report script

Worked example

Type this into ComponentReport.cs. It is the lab file, trimmed to what the lesson needs.

using UnityEngine;

public class ComponentReport : MonoBehaviour
{
    void Start()
    {
        Component[] parts = GetComponents<Component>();
        Debug.Log($"{name}: {parts.Length} components");

        if (GetComponent<Rigidbody>() == null)
            Debug.Log("no Rigidbody - physics is opt-in");

        Debug.Log($"this = {GetType().Name}, gameObject = {gameObject.name}");
    }
}

Line 7 asks the object what it is made of

Why: GetComponents (plural) returns every component; GetComponent (singular) returns the first of one type, or null.

Line 10 is the physics claim, checked

Why: A null result is not an error here - it is the answer.

lineprints on a plain cubeprints on a cube with a Rigidbody
7PlainCube: 5 componentsPhysicalCube: 6 components
10no Rigidbody - physics is opt-in(nothing - the branch is skipped)
13this = ComponentReport, gameObject = PlainCubethis = ComponentReport, gameObject = PhysicalCube

43. Fill in the missing half

Faded example

Here is the second lab script with two holes in it. Same shape as the one you just typed.

Fill in the blanks

public class ActiveVsDestroy : MonoBehaviour
SetActive}(false);
Destroy(toDestroy);
}
}
}

Why: SetActive is a method ON a GameObject, so it is called through the reference: toDeactivate.SetActive(false). Destroy is inherited from Object, so it is called as a plain method with the victim as the argument: Destroy(toDestroy). That asymmetry is worth noticing - it is why the two calls look so different for such similar-sounding jobs.

44. Step 3: wire it up and watch the Hierarchy

Worked example

Two more cubes and an empty object to drive them.

  1. Two cubes named WillBeDeactivated and WillBeDestroyed
  2. GameObject > Create Empty, name it Lab Driver
  3. Attach ActiveVsDestroy to the driver
  4. Drag each cube into the matching slot in the Inspector
  5. Press Play and watch the Hierarchy, not just the Game view
at t = 2s, in the Hierarchywhat you see
WillBeDeactivatedstill listed, name goes grey
WillBeDestroyeddisappears from the list
Lab Driverunchanged - it did the doing
Consoletwo PASS lines confirming both

The Hierarchy is the honest view. The Game view cannot tell you the difference between 'switched off' and 'gone', because both are invisible.

45. Where this shows up in a real game

Real world

Discussion prompt

You are building a level with 40 enemies, 200 coins, a pause menu and a boss that appears at the end. For each of the four, would you deactivate it, destroy it, or never do either? Say why.

Answer:

  • Enemies - destroy on death. They do not come back, and 40 corpses is 40 objects still in the scene.
  • Coins - destroy on collection, or deactivate if you pool them for the next round. This is the one where either answer can be right, and pooling is the reason.
  • Pause menu - always deactivate. It comes back every time you press Escape, and rebuilding it from scratch would lose its state.
  • Boss - deactivate at the start, activate when the fight begins. It has to exist beforehand so the Inspector references pointing at it are wired up.

That last one is the practical reason SetActive exists: an object that is not needed yet, but whose references have to be in place before it is.

46. Reading your own Console output

Concept

The lab prints through one helper so the output reads as a report. Learn the three prefixes now - every later lesson uses them.

[L01] ======  component report for 'PlainCube'  ======
[L01] ----  5 component(s): Transform, MeshFilter, MeshRenderer, BoxCollider, ComponentReport
[L01] PASS  every GameObject has a Transform
[L01] PASS  no Rigidbody on this object - physics is something you ADD
[L01] FAIL  expected 3 components, found 4
prefixmeanswhat to do
----an observationread it
PASSa claim about Unity that heldnothing
FAILthe scene is not set up as the lesson assumesread the message - it names what it expected

47. Predict the next line

Pattern

You add a second ComponentReport to the same cube and press Play.

Predict first

What does the Console show?

  • One report, unchanged
  • One report, now saying 6 components
  • Two identical reports, each saying 6 components
  • An error - you cannot add two of the same script

Correct: Two reports, each saying 6 components.

Why: Callbacks are per component, not per object, so both instances run Start. And each one counts the other, so the total is six. Unless a script is marked [DisallowMultipleComponent], duplicates are allowed - which is a real source of 'why did this happen twice?' bugs.

48. Explain it to someone a week behind you

Explain it

Discussion prompt

A friend asks: 'I made a Coin.cs script but nothing happens when I press Play.' Answer them in three sentences, without using the word 'component' more than once.

Answer:

A model answer: 'A script file on its own is just a description - Unity has not been told to use it anywhere. Drag it onto an object in the Hierarchy, or use Add Component on that object. Now there is an actual copy of your script running on that object, and Start will fire.'

The idea to land: a class is a definition; attaching it creates an instance. Unity only ever runs instances.

49. Now break it, on purpose

Concept

Each of these takes twenty seconds and kills one wrong belief for good.

do thiswhat you expectwhat happens
Delete the Rigidbody from the falling cubeit still fallsit hangs in the air
Untick the checkbox beside your script onlythe object switches offonly that script stops
Untick the checkbox at the top of the Inspectorthe script stopsthe whole object stops
Write a script and attach it to nothingit runsnothing happens at all

50. Make the call before you run it

Hypothesis

You untick the checkbox beside ComponentReport in the Inspector - the component's own checkbox - and press Play.

Predict first

Does Start run?

  • Yes
  • No
  • Only if the object is active
  • It throws

Correct: No. Start does not run on a disabled component.

Why: Start and Update are skipped for a disabled component. Awake is the exception: it runs even on a disabled component, because Awake is about the object being created rather than about it running. That single exception is why lesson 4 tells you to cache in Awake and reach out in Start.

51. The procedure: diagnosing any 'it doesn't work'

Pattern

Nine times out of ten in Unity, nothing is wrong with your code. Something is not attached, not enabled, or not assigned.

  1. Is the object active? Check the top-left checkbox in the Inspector, and check every parent above it.
  2. Is the component enabled? Check the checkbox on that component's own row.
  3. Is the script attached at all? A file in Assets does nothing. It must be a row in some object's Inspector.
  4. Is the reference assigned? An empty slot in the Inspector is a null - the number one runtime error.
  5. Does the object have what the code assumes? GetComponent<T>() returns null when there is no T.
  6. Is anything printing? Put a Debug.Log in Start. If it never appears, the problem is one of the five above, not your logic.

Work down that list before you read your own code again. It is faster, and it is what an experienced developer does automatically.

52. Check 1: what is a GameObject?

Check

Answer before you click.

Check your understanding

Which statement is the most accurate description of a GameObject in Unity?

  • A. A base class that Cube, Camera and Light inherit from, each adding their own behaviour
  • B. A named container with a Transform, whose every other capability comes from attached components (correct)
  • C. A visible object in the scene - anything invisible is not a GameObject
  • D. A script you write that Unity runs once per frame

Answer: B

Why: There is exactly one GameObject type. A Camera is a GameObject with a Camera component; a Cube is a GameObject with a Mesh Filter, Mesh Renderer and Box Collider. Composition, not inheritance - which is why you attach your script rather than subclassing anything.

Why A tempts people
The inheritance model. It is how most object-oriented tutorials work, but Unity composes instead: there is no Cube class to extend, and Camera is a component, not a subclass.
Why C tempts people
Plenty of GameObjects are invisible - empty parents used for organisation, trigger zones, spawn points, and any object whose Mesh Renderer you removed.
Why D tempts people
That describes a MonoBehaviour, which is a component you attach TO a GameObject. Your script rides on the object; it is not the object.

53. Check 2: the cube that will not fall

Check

A cube in a scene, Play pressed, nothing moves.

Check your understanding

A cube sits in mid-air with a Transform, Mesh Filter, Mesh Renderer and Box Collider. You press Play and it does not move. What is the fix?

  • A. Tick 'Use Gravity' on the Box Collider
  • B. Add a Rigidbody component (correct)
  • C. Set the Transform's Y position to fall over time in Update
  • D. Nothing is wrong - it needs a floor to fall towards

Answer: B

Why: Gravity in Unity is applied to Rigidbodies, not to GameObjects. Without one the cube is not part of the simulation at all, so there is nothing for gravity to act on. Adding a Rigidbody is what hands its position to the physics solver.

Why A tempts people
A Collider has no Use Gravity setting - that field lives on the Rigidbody. This is the collider-implies-physics confusion: a Collider is a shape, not a simulation.
Why C tempts people
That would move it, but by writing the transform - the exact thing lesson 3 shows walks straight through walls. If you want physics, ask for physics.
Why D tempts people
Falling does not need a destination. An object with a Rigidbody in an empty scene falls forever.

54. One question to sit with

Socratic

Discussion prompt

Unity chose composition (attach components) over inheritance (subclass a base type). Name one thing that becomes easy under composition which would be awkward under inheritance.

Hint: Think about an object that needs to be two things at once.

Answer:

A door that is also a light source that is also a save point. Under inheritance you would need a LightEmittingSaveDoor class, and the next combination needs another one.

Under composition you attach three components to one GameObject and you are done. The combinatorial explosion never happens - which is why nearly every game engine written since 2005 works this way.

55. Check 3: switched off or gone?

Check

The last one. Take your time.

Check your understanding

You call enemy.SetActive(false) at t = 2s. At t = 3s, which of these is true?

  • A. enemy == null is true, and OnDestroy has run
  • B. enemy == null is false, the enemy is still in the scene, and OnDisable has run (correct)
  • C. enemy == null is false, and the enemy's Update is still running
  • D. The enemy is removed from the scene but the reference stays valid

Answer: B

Why: SetActive(false) stops the object running - no Update, no rendering, no collisions - and fires OnDisable. It does not remove anything: the object stays in the scene with its components and values intact, so the reference is still valid and SetActive(true) restores it.

Why A tempts people
That is what Destroy does. Nothing was destroyed here, so OnDestroy has not run and the reference is very much alive.
Why C tempts people
An inactive GameObject runs no Update at all. That is the point of deactivating it.
Why D tempts people
It is the other way round: the object stays and the reference stays. Destroy is the one that removes the object, and then the reference does NOT stay valid.

56. A rough number, not a right one

Estimation

A level has one player, 40 enemies, 200 coins, 60 pieces of scenery, 12 lights and a UI canvas with 30 elements.

Predict first

Roughly how many of those GameObjects need a Rigidbody?

  • About 340 - everything physical
  • About 240 - everything that moves or is hit
  • About 40 - the things that move under physics
  • Zero

Correct: Around 40, and possibly fewer.

Why: Enemies that are pushed around by the simulation need one. Coins usually need only a trigger collider. Scenery, lights and UI need nothing. Rigidbodies cost simulation time every fixed step, so the habit of adding one to everything is both a performance problem and the source of the tunnelling bugs in lesson 3.

57. What this unlocks

Concept

Everything after this is a component. Prefabs are saved component trees; physics is one component; your gameplay code is a component. The container never gets more complicated than it is right now.

next lessonthe question it answers
2 - Prefabshow do I make fifty of these and change them all at once?
3 - Rigidbodywhat does 'has physics' actually mean?
4 - Lifecyclewhen does Unity call my code?
5 - GetComponenthow do I reach one component from another?

58. Connect it to something you already know

Analogy

If you have written any object-oriented code before, this maps onto something familiar.

Match the pairs

Match the Unity idea to its closest cousin outside Unity.

  • u1. GameObject
  • u2. Component
  • u3. Attaching a script
  • u4. Prefab (next lesson)
  • o1. an empty struct that holds a list of interfaces
  • o2. one implemented behaviour with its own state
  • o3. instantiating a class and registering it
  • o4. a saved constructor call with all its arguments

Why: The pattern has a name outside Unity: entity-component composition. The GameObject is the entity - an identity with no behaviour. Components supply behaviour and state. Recognising it as a known pattern rather than a Unity quirk makes the rest of the engine much easier to predict.

59. Draw the model

Connect it up

Draw it

Draw a GameObject as a box with its name in it, then hang every component from part 1 off it as a labelled card. Beside each card, write the one thing that stops working if you remove it.

60. Before you close this

Exit ticket

Predict first

Which of these four are you least sure of right now?

  • What a GameObject is made of
  • Why physics is opt-in
  • SetActive vs enabled vs Destroy
  • Why a script file does nothing until attached

Correct: Whichever you picked - that is the one to bring to the session and the one to re-run in the lab scene.

Why: The diagnostic marked this topic Fragile, and fragile means the answers were right while the confidence was low. Naming the shakiest piece out loud is what turns a lucky guess into knowledge, so bring the one you picked to the next session and we will build the scene for it from scratch.

61. What you can now do

Recap

You can describe a GameObject without hand-waving, and you can predict what a cube will do from its Inspector alone.

Lab: unity-labs/Assets/NaruhodoLabs/Lesson01_GameObjects/SETUP.md. Build the scene, run the 'now break it' table, then go to lesson 2.

Sources

  1. Unity Manual - GameObjects
  2. Unity Manual - Introduction to components
  3. Unity Scripting API - GameObject.SetActive
  4. Unity Scripting API - Object.Destroy
  5. Unity Scripting API - GameObject.GetComponent
  6. Naruhodo Unity Labs - Lesson 01 setup notes — unity-labs/Assets/NaruhodoLabs/Lesson01_GameObjects/SETUP.md

Want this taught 1-on-1? Alexander tutors Unity Game Engine — $55/session, free consultation.

Book on Wyzant · Text (657) 465-8108