A cube that moves when you press Play is a useful first milestone: it connects what you see in the Unity Editor with what you write in C#. Drawing on Zenva’s experience teaching coding and game development across more than 400 courses, this Unity for beginners tutorial builds toward that milestone one step at a time. You’ll install Unity, practice building and testing a 3D scene, and finish by moving a GameObject with a vector.
Download Project Files
You can follow this tutorial from a blank Unity project. The project files and the full project are available through the course included in the Unity Game Development Mini-Degree.
Unity for Beginners: Install Unity and Create a Project
Installing the Unity Hub
Unity Hub and the Unity Editor do different jobs. The Hub manages your projects and installed editor versions; the Editor is where you build your game. Install the Hub first, then use it to install the Editor.
Downloading the Unity Hub
Go to Unity.com and select the blue Plans and pricing button in the upper-right corner.

Scroll to Personal, the free edition for individuals, and choose Download now.

On the download page, pick the installer for your operating system, such as Download for Windows or Download for Mac.

Installation and Account Setup
Open the downloaded setup file.

Follow the installer prompts and choose where to install the Hub.

Open Unity Hub when setup finishes. If you don’t already have a Unity account, choose Create account and finish registering on Unity’s website. Then return to the Hub and sign in.

If Unity asks you to activate a Personal license, choose Agree. The Hub then takes you to Installs.

Installing the Unity Editor
On Installs, select Install Editor to see the available versions.

Find the latest Recommended Version and click Install next to it.

Keep Microsoft Visual Studio selected so you have a code editor for the C# exercises. You can also select build-support modules for platforms you want to target:
- Android Build Support
- iOS Build Support
- Linux Build Support
- Mac Build Support
Click Continue once you’ve chosen the modules.

Accept the terms and click Install to confirm.

You can follow the installation in Downloads. Once it’s complete, you’re ready to start a project in the Hub.

Start a Project in the Hub
Creating a New Project
Check that your editor version now appears under Installs.

Then switch to Projects near the top left of the Hub.

This is where you’ll come back to open, manage, or update your projects.

Click New project. If you already have projects in the list, look for the button in the upper-right corner.

Understanding Project Templates
The template picker lets you choose how Unity sets up the new project.

Under Core, you’ll see options such as:
- 2D
- 3D
- 3D (Mobile)
- VR (Virtual Reality)
- AR (Augmented Reality)
A template gives you a starting configuration, not a permanent restriction. You can start with a 2D template, for example, and still add 3D elements later.
Configuring Your Project
Choose Universal 3D for this walkthrough.

Fill in the fields on the right:
- Unity Organization: Select your Unity account from the dropdown.
- Project Name: Give the project a recognizable name, such as Intro to Unity 2025.
- Location: Choose where Unity should save the project. A folder such as Unity Projects makes future projects easier to find.

Launching the Editor
Click the blue Create Project button.

Accept the software terms if Unity asks again.

Allow a few minutes for the first launch while Unity imports the template assets and prepares the project.

Once the Editor opens, take a moment to find the panels in the next section before you start changing the scene.

Find Your Way Around the Unity Editor
Editor Overview – Part 1
Open your project in Unity and take a moment to locate the windows you’ll use to build and test a scene. The Scene window shows where objects are, the Hierarchy shows what’s in the scene, and the Inspector shows what you can change about the object you select.
The Editor Layout
Start with Unity’s default layout. Find these four windows before you begin moving things around:
- The Hierarchy Window
- The Scene Window
- The Inspector Window
- The Project Window

To give a window more or less room, click and drag its border. Try widening the Scene window to give yourself more room to work in it.

To undo the layout change, open the Editor Layout dropdown in the upper-right corner of the editor and choose Default. The windows return to their original arrangement.

The Scene Window
Look in the center of the editor for the Scene window. This is the workspace where you can look around and edit the game world directly.

Use the Scene window to build a level: place objects, change their positions, and arrange them in relation to one another. In a 3D project, you’ll work in a three-dimensional view. In a 2D project, the workspace looks more like a flat grid.
The Game Window
To see how that same scene looks to a player, click the Game tab next to Scene.

Compare the two views. In the Scene window, you choose where to look as you work. In the Game window, you see only what the game’s camera renders.

Click Play at the top of the editor. Unity runs the game and displays it in the Game window, where you can try it as a player. Click Play again to stop.

The Hierarchy Window
Return to the Scene tab and find the Hierarchy on the left. Use this list to find an object by name instead of looking for it in the scene itself.

The Hierarchy lists every GameObject in the currently open scene. Think of a scene as a level in your game. Click an entry in the Hierarchy and watch for two changes: the GameObject is highlighted in the Scene window, and its settings appear in the Inspector.
The Inspector Window
With a GameObject selected, look at the Inspector, usually on the right. Its settings are grouped into components. These are the parts of a GameObject that determine what it does, and you can edit their properties here.

Select a few GameObjects in the Hierarchy and compare what the Inspector shows. Look for these components:
- Transform Component: Every GameObject has a Transform. It determines where the object is, how it’s rotated, and how it’s scaled in the game world.
- Camera Component: Select a camera to find the component that renders its view of the game world. You can adjust settings such as the field of view here.
- Light Component: Select a light to find settings for its color, intensity, and other lighting properties. A Directional Light, for example, can act as the sun in your scene.
As you switch between a camera and a light in the Hierarchy, notice that both still have a Transform, but the other settings reflect what that object does.

Editor Overview – Part 2
The Hierarchy tells you what’s in the open scene. To find the files that make up the project or check what Unity reports as you work, look at the Project and Console tabs along the bottom.
The Project Window: Your Asset Manager
Click the Project tab. This window works like a file explorer for the assets in your game project.

Assets are the files you build the game with, including 3D models, sound effects, textures, and scripts. Use the Project window to browse those files, import or create assets, and organize them into folders.
- Open a folder: Double-click a folder to see the files and folders inside it.
- Move between folders: Use the folder tree on the left to jump to a different folder. To go back to a parent folder, click its name in the breadcrumb path at the top of the window.
- Inspect an asset: Select a material or a 3D model. Its properties appear in the Inspector, where you can review or change its settings, just as you would for a GameObject selected in the Hierarchy.
The Console: Your Debugging Hub
Now click Console, next to the Project tab. This is where you can check what the editor and your game are reporting.

When something doesn’t work as expected, use the Console to see whether Unity has logged a problem or whether a message from your own code can help explain what happened.
- Errors: Check for errors in your code or problems that Unity encountered in the editor.
- Warnings and messages: Look here for editor notices, such as a warning about a potential problem importing an asset.
- Messages from your code: Add logging to test whether a piece of code runs or to see how the value of a variable changes while the game is running.
Customizing the Editor Layout
To move a window rather than resize it, drag its tab. Try dragging the Console tab out of its default position.

Dock the Console in a separate panel beside the Project window so you can read messages and browse assets at the same time. You can dock a window as a tab within another panel, or drag it to an edge to give it a panel of its own.

To change the whole arrangement at once, open the Layout dropdown in the upper-right corner of the editor.

Try the presets in the menu to see how they change your workspace:
- Default: Restore the standard arrangement, including the original positions of the Project and Console tabs.
- 2 by 3: Try this preset if the standard arrangement doesn’t suit how you want to work.

- 4 Split: See the scene from four viewpoints at once, such as top, front, side, and perspective.

- Tall: Try this arrangement when you’re working on a vertically oriented monitor.
If none of the presets suits you, choose Default again and move or resize the individual windows you want to change.
Using the Playback Controls
When you’re ready to test the scene, find Play, Pause, and Step at the top center of the editor.

- Play: Start the game. Unity switches from the Scene view to the Game view so you can interact with the game as a player. Click the same button again when you’re ready to stop and return to edit mode.

- Pause: Freeze the game on its current frame to inspect a specific moment without the action moving on.
- Step: With the game paused, click this button to advance one frame. Click it again for each additional frame you want to inspect, for example when an animation or fast-moving sequence is hard to follow at full speed.
Scene Navigation
After testing the game, switch back to the Scene view to work on the level. The controls below move the editor camera so you can inspect the scene from different angles without moving any GameObjects.
Basic Camera Movement
Move your pointer over the Scene view. Start by looking around from where you are, then use the keyboard to move through the scene as you would in a first-person game.

- Look Around: Hold the right mouse button and drag. Dragging rotates the editor camera so you can look in a different direction.

- Fly Around: Keep holding the right mouse button while you use these keys to move the camera:
- W: Fly forward.
- S: Fly backward.
- A: Fly to the left.
- D: Fly to the right.

To change height while flying, keep the right mouse button held and use these keys:
- E: Fly up.
- Q: Fly down.

Try turning with the mouse while holding W to fly toward another part of the scene, then use E or Q to view it from higher or lower down.
Zooming and Panning
When you’re already looking at the right part of the scene, use zoom or pan to adjust the framing without flying through it.
- Zoom: Roll the mouse wheel to move the view in or out around the camera’s current focal point.

- Pan: Hold the middle mouse button and drag. The view shifts sideways or up and down without turning the camera.

Focusing On Objects
If you lose track of an object in a large scene, select it by name in the Hierarchy. If you can already see the object, you can also click it directly in the Scene view.

With the object selected, press F. The editor camera jumps to a view that frames the object, so you don’t have to find it by flying or zooming.

The Orientation Gizmo
To line up a view with one of the scene’s axes, find the Orientation Gizmo in the upper-right corner of the Scene view.

Each color represents an axis: red for X, green for Y, and blue for Z. Click a colored cone to align the editor camera with that axis. Try the green Y cone: the scene snaps to a top-down view, as if you’re looking straight down on it from above.


Perspective and Orthographic Views
Use the cube in the center of the Orientation Gizmo to switch between Perspective and Orthographic projection. Compare how the same scene looks in each mode.

- Perspective View: In this default mode, objects look smaller as they get farther away, much as they do when you look around in the real world. That change in apparent size helps you judge depth.

- Orthographic View: Distance no longer changes an object’s apparent size. The same object looks equally large from one meter away or one kilometer away. Use this mode for 2D games or when you need to position objects precisely in a top-down or side-on view.

Summary of Navigation Controls
- Look around: Drag with the right mouse button held.
- Fly through the scene: Keep the right mouse button held and use W, A, S, and D to move, or Q and E to change height.
- Zoom: Roll the mouse wheel.
- Pan: Drag with the middle mouse button held.
- Frame an object: Select it and press F.
- Align the view: Click a colored axis on the Orientation Gizmo.
- Switch projection: Click the cube at the center of the Orientation Gizmo to toggle between Perspective and Orthographic.
Create and Transform GameObjects
GameObjects
Look around a Unity scene and you’ll find GameObjects wherever you look: the camera, the lights, the characters, and the objects that make up the environment. To see what each one does, start with the objects in a new scene.
GameObjects and Scenes
Think of a scene as a level in your game. A new Unity project typically opens with a scene named SampleScene.

Open the Hierarchy to see which GameObjects belong to the current scene. Depending on how the scene was created, you may already see these three:
- Main Camera: Renders the view that appears on the player’s screen.
- Directional Light: Lights the scene as if the light came from a distant source, such as the sun.
- Global Volume: Applies post-processing effects across the scene.

Click any GameObject in the Hierarchy. Unity highlights the object in the Scene view and opens its properties in the Inspector, where you can see what it contains.

The Role of Components
A GameObject is a container. The scripts and modules attached to it, called components, give it specific features or behaviors. Select the default objects one by one in the Hierarchy and compare their components in the Inspector:
- Select Main Camera to find the Transform alongside the Camera component.

- Select Directional Light to see a Transform paired with a Light component instead.

- Select Global Volume to find another Transform, this time alongside a Volume component.

All three have a Transform because every GameObject needs a position, rotation, and scale in 3D space. It’s the other components that set them apart. For instance, the Camera component renders what it sees, while the Light component emits light.
Creating and Modifying GameObjects
Add a GameObject of your own so you can try editing its components. Start by clicking the plus (+) icon at the top of the Hierarchy.

The menu lists the types of objects you can create. Choose 3D Object > Cube for this example.

Look for the new Cube entry in the Hierarchy and the corresponding cube in the Scene view.

Select Cube in the Hierarchy to inspect its components. Here’s how the standard cube’s components work together:
- Transform: Places, rotates, and scales the cube in the scene.
- Mesh Filter: Holds the model data that defines the cube’s 3D shape.
- Mesh Renderer: Draws that shape on screen using the assigned material.
- Box Collider: Gives the cube a physical shape for collision detection and physics.

For an object that marks a location or organizes a group rather than providing a visible shape, create an empty GameObject. It starts with only a Transform, which is enough for uses such as marking a waypoint.


To give an existing GameObject another feature, select it and click Add Component at the bottom of the Inspector. Search for the component you need. For example, choose Audio Source if the object should play sounds.


Modifying Component Properties
Each component’s settings are called properties. Editing them in the Inspector changes how the GameObject looks or behaves. Reselect the cube and try these two kinds of changes:
- Under Transform, type a new value for any axis under Position, Rotation, or Scale. You can also click and drag an X, Y, or Z label to adjust the value interactively.
- Under Box Collider, adjust the Size fields. This lets you make the collision area larger or smaller than the visible mesh.

To remove a GameObject, select its entry in the Hierarchy and press Delete. The object disappears from both the list and the scene.

Try adding a few different GameObjects and changing their component properties to see which settings affect their appearance or behavior. Next, use the Transform to place an object at a specific point in the scene.
Moving GameObjects
The XYZ Coordinate System
Picture a 2D graph with X running horizontally and Y running vertically. Unity adds Z for depth, so you need all three coordinates to pin down a point in a 3D scene. The axes meet at the world origin, where X, Y, and Z are all zero: (0, 0, 0).

Creating an Object and Using the Transform Component
To see the coordinates in action, create another cube. This time, right-click in the Hierarchy and choose 3D Object > Cube from the menu. The new Cube GameObject appears in the scene.

Select the new cube and find Transform in the Inspector. The Position row shows its current location as three editable fields, one each for X, Y, and Z.

Enter 0 in each Position field. The cube moves to the world origin.

Leave Y and Z at zero and enter 5 for X. The cube moves five units to the right of the origin without changing its height or depth. A Unity unit generally corresponds to one meter, so you can use the Inspector fields to place objects at measured distances.

The Move Tool
If you’d rather place the cube by eye, keep it selected and switch to the Move Tool to work in the Scene view. Click its icon in the toolbar at the top left of the editor or press W.

Look for the three colored arrows on the selected cube. Together they form the Move Tool’s gizmo. Each arrow follows one axis:
- Red (X): Left and right.
- Green (Y): Up and down.
- Blue (Z): Forward and backward.

Click and drag one arrow. The cube follows that axis while its position on the other two axes stays the same.

To move on two axes at once, drag one of the three small colored squares between the arrows. Each square constrains movement to a plane. Try the green square: the cube slides along X and Z without changing its Y position.

Grid Snapping for Precision
Dragging works well for rough placement. For level geometry that needs to line up, turn on grid snapping instead. Find the Grid and Snap settings in the toolbar at the top of the Scene view and click the magnet icon. Click it again whenever you want to turn snapping off.

With snapping on, drag the cube with the Move Tool. Instead of sliding freely through the scene, it jumps from one grid point to the next.

To change the spacing between those points, click the small arrow next to the snapping icon. Edit the Move values for X, Y, and Z to set the grid size on each axis.

Use those increments to line up pieces such as walls, doors, and other modular assets.
Summary
Choose the placement method that fits the job: type coordinates into Transform > Position when you know the exact location, or use the Move Tool to place the object in the Scene view. Leave snapping off for free movement and turn it on when objects need to share grid alignment.
Rotating GameObjects
Once an object is in place, use the Rotation Tool to change which way it faces.
Accessing the Rotation Tool
Create a fresh cube to practice. Click the plus (+) icon in the Hierarchy and choose 3D Object > Cube.

Select the new cube. In the toolbar at the top left of the Unity Editor, click the rotation icon. You can also switch to the Rotation Tool by pressing E.

The arrows you used to move the cube give way to a rounded gizmo made up of colored rings.

Using the Rotation Gizmo
The axis colors carry over from the Move Tool. Here, dragging a colored ring turns the cube around an axis instead of moving it along one:
- Red ring: Drag to turn around the X-axis.
- Green ring: Drag to turn around the Y-axis.
- Blue ring: Drag to turn around the Z-axis.

Watch Transform > Rotation in the Inspector as you drag a ring. The numbers change as the cube turns. Unlike the Position fields, these values describe angles and are measured in degrees.

You can also rotate without picking one of the three axis rings:
- Outer circle: Drag the light gray ring around the gizmo to rotate the cube relative to your current viewing angle in the Scene view.

- Inner sphere: Drag inside the colored rings for free-form rotation across multiple axes. Use this when you want a quick, approximate orientation rather than a specific angle.

When you know the angles you want, skip the gizmo. Enter them in degrees in the X, Y, and Z fields under Rotation in the Inspector.

Understanding Local vs. Global Coordinates
The tool handles can follow either the selected object’s axes or the world’s axes. Comparing the two on a rotated object makes the difference easier to see.
Use the Rotation Tool to tilt the cube so its sides no longer align with the world axes.

With the tilted cube still selected, press W to switch back to the Move Tool.

If the editor is set to Local, the Move Tool’s arrows tilt with the cube. The green arrow points along the cube’s own Y-axis, so dragging it moves the cube in its own version of “up,” not straight up in the scene.

For movement along the scene’s axes, find the Local button at the top left of the Scene view toolbar. In Global space, Y points up and Z points forward regardless of the cube’s rotation.

Click Local to switch the setting to Global.

Look at the arrows again. The cube stays tilted, but the Move Tool’s gizmo now lines up with the world axes.

The same setting changes the Rotation Tool’s rings. Switch to that tool in Global mode and drag the green ring to rotate around the world’s Y-axis instead of the cube’s tilted Y-axis.

The Local/Global toggle changes the Scene view gizmos, not the Inspector fields. For the cube in this example, the Position fields still use world coordinates whichever setting you choose.

Scaling GameObjects – Part 1
Accessing the Scale Tool
Use a fresh cube to compare what happens when you resize one dimension versus all three. Right-click in the Hierarchy and choose 3D Object > Cube.

Select the cube, then switch to the Scale Tool using either of these methods:
- Press R on your keyboard.
- Click the Scale Tool icon in the toolbar at the upper left of the editor.

The Scale gizmo has three axis lines like the Move gizmo, but the lines end in small cube handles rather than arrows.

How to Use the Scale Tool
Choose a handle based on the dimension you want to change. The handles use the same axis colors as the other transform tools:
- Red: Resizes the object along X.
- Green: Resizes it along Y.
- Blue: Resizes it along Z.
Drag one of the colored cube handles. The object stretches or shrinks along that axis without changing size along the other two.

Glance at Transform > Scale in the Inspector while you drag. The field for that axis updates as the cube changes size.

To make the whole object larger or smaller without changing its proportions, drag the cube handle at the center of the gizmo. This scales all three axes together.

Understanding Scale Values
Compare the three rows in the Transform component. Position and Rotation often start at zero, but a new object’s Scale starts at (1, 1, 1).

The reason is that each scale value multiplies the object’s original size along that axis:
- 1 keeps that dimension at 100% of its original size.

- 2 doubles that dimension.

- 0.5 reduces that dimension to half its original size.

A Note On Local vs. Global Space
Rotate the cube and then switch to the Scale Tool. Its handles line up with the cube’s tilted axes. Try switching between Local and Global in the toolbar: unlike the Move and Rotate gizmos, the Scale gizmo doesn’t change orientation.

That’s because the Scale Tool resizes an object along its own dimensions. You still stretch or shrink the cube along its local axes, even with the toolbar set to Global.
Challenge: Create a Stick Figure
Combine the Move, Rotate, and Scale tools to build a stick figure from simple 3D shapes.
- Add a few primitive GameObjects. For example, use cubes for the torso and limbs and a sphere for the head.
- Arrange the shapes so the figure has a head, a body, two arms, and two legs.
- For each part, use the Move Tool to place it, the Rotate Tool to angle it, and the Scale Tool to get the dimensions you want.

Use the figure above as a reference rather than a template. Try arranging the parts yourself, then compare your approach with the walkthrough below.
Scaling GameObjects – Part 2
In this version of the stick figure, a scaled cube forms the torso. Copies of it become the legs and arms, and a sphere completes the head.

Creating the Body
Start with the torso. Right-click in the Hierarchy and select 3D Object > Cube to add the shape that the other parts will build on.

Select the new cube, then press R or click the Scale Tool icon in the toolbar to bring up its handles.

Drag the Scale handles to make the cube narrower and taller. Aim for a slim, upright torso.

With the torso selected, use the name field in the Inspector to rename the object Body. This makes it easy to pick out in the Hierarchy when you need a copy.

Adding the Legs
Use the torso as a starting shape for the first leg. Select the Body cube in the Hierarchy.

Press Ctrl + D. A copy appears in the Hierarchy with (1) added to the original name.

In the Inspector, rename the copy Leg so it’s clear which object you’re about to reshape.

Switch to the Move Tool and drag the leg down below the torso and out to one side.

Press E for the Rotate Tool. Angle the leg so it extends down and away from the body.

Press R and use the Scale Tool to shrink the leg until it looks proportional to the torso.

Once the first leg is positioned and sized, select it and press Ctrl + D to start the second leg from the same shape.

Move the copy to the opposite side of the torso and rotate it to fit. If you’re having trouble matching the angles, hold Ctrl while rotating or scaling to snap the adjustment to fixed increments.

To choose different increments, open the snapping options at the top right of the editor toolbar and adjust the snap settings.

Before moving on, check that both legs extend from the lower part of the torso, one on each side.

Constructing the Arms
This time, use one object for both arms. Go back to the original Body cube in the Hierarchy, select it, and duplicate it again.

Rename this copy Arms to distinguish it from the upright torso.

Rotate Arms by 90 degrees so the long side runs horizontally.

Switch to the Scale Tool. Make the shape thinner and stretch it sideways so the ends can serve as the two arms.

With the Move Tool, slide the arms into place across the upper torso. Each end should stick out on a different side of the body.

Adding the Head
Give the figure a round head to contrast with the cube-based body and limbs. Right-click in the Hierarchy and choose 3D Object > Sphere.

Rename the sphere Head so it appears alongside the other named parts in the Hierarchy.

Use the Move Tool to bring the sphere up to the top of the torso.

Resize it with the Scale Tool until it looks proportional to the figure. If changing its size leaves it too high or too low, switch back to the Move Tool and adjust its placement.

Check the silhouette in the Scene view: you should see a round head above a narrow torso, with arms across the top and two legs below.

Grouping and Positioning the Figure
Instead of moving each finished part separately, select the whole figure. With all its parts selected, you can move, rotate, or scale them together. Use whichever selection method suits your view:
- Click and drag: Draw a selection box in the Scene view that encloses every part of the figure.

- Ctrl + Click: Hold Ctrl in the Hierarchy and click each GameObject that belongs to the figure.
- Shift + Click: If the parts are listed together in the Hierarchy, click the first one, such as Body. Then hold Shift and click the last one, such as Head, to select both entries and everything between them.

With the full figure selected, use the transform tools to place and adjust it in the scene. Try moving it first: every selected part should travel together so the figure stays assembled.

Group GameObjects With Parenting
Parenting – Part 1
Parent and Child GameObjects
When one GameObject needs to follow another, make it a child of that object. In Unity, a child GameObject has its own local position, rotation, and scale, all relative to its parent. Changing the parent’s Transform carries the child along without taking away the child’s ability to be positioned, rotated, or scaled on its own.
Set up a simple scene to see the difference. Add a Capsule to stand in for a player character who will hold an item.

Rename the Capsule Player so you can identify it in the Hierarchy.

Add a Cube as a separate GameObject to represent the object the player will carry.

Rename the Cube Item. The two objects are still independent at this point.

In the Scene view, scale the Item and position it in front of the Player so it looks like the character is holding it.

Test the setup by selecting the Player and moving it in the scene. The Item stays where you placed it, even though it looked attached a moment ago.

To keep the Item in front of the Player as the Player moves, make the Item a child of the Player.
How to Create a Parent-Child Relationship
In the Hierarchy, click and drag the Item GameObject directly onto Player.

Release the mouse button and check the Hierarchy: Item should now appear indented beneath Player. That indentation tells you Item is the child and Player is the parent. Use the small arrow next to Player to show or hide its children.

Select Player again and try moving, rotating, and scaling it. This time, Item follows each change because its Transform is relative to Player.

Understanding the Hierarchy
Now select Item instead of Player and move it on its own. Only Item changes position. Transform changes travel from the parent to its children, not from a child back up to its parent.

A GameObject can be a child and a parent at the same time. To see how that works, duplicate Item and make the new copy a child of the original Item. The Hierarchy should now have three levels:
- Player (grandparent)
- Item (parent)
- Item (1) (child)
- Item (parent)

Start at the top and move Player. Both Item and Item (1) follow, even though only the original Item is a direct child of Player.

Next, move the original Item. Item (1) moves with it, while Player stays in place.

Finally, move Item (1). Neither of the objects above it moves; the change affects only the copy.

Practical Applications
Use the same arrangement whenever parts need to stay together as a group:
- Parent equipment such as items, weapons, or armor to a character so it moves with them.
- Group related UI elements under a panel.
- Keep an audio source or particle effect attached to an object as it moves.
- Build an object, such as a vehicle, from separate pieces that need to move together.
Challenge
Try building a sword from three Cube GameObjects. Use each cube’s Transform to position, rotate, and scale it into one of the three pieces: the blade, the cross-guard, or the hilt.

Once the parts look like a sword, arrange them in a parent-child hierarchy. Your test is to select and move just one root object and see all three pieces move with it.
Parenting – Part 2
With the sword, there are two ways to group the pieces: make the hilt the parent or put all three parts under an empty GameObject. Build the sword first so you can try both arrangements.
Creating the Sword Components
Start with the hilt. Add a basic 3D Cube to the scene by choosing GameObject > 3D Object > Cube.

In the Inspector, set the cube’s Position to (0, 0, 0) to center it in your workspace.

Scale the cube until it has the proportions of a sword handle. This is the hilt that the other pieces will line up with.

With the hilt selected, press Ctrl+D or Cmd+D to duplicate it. Use this copy to make the cross-guard.

Move the copy up, rotate it 90 degrees on one axis, and adjust its scale so it forms a guard across the handle.

For the blade, duplicate one of the cubes you already have. Move the new copy above the guard, then scale it into a long, thin shape.

Check the result in both views. In the Scene view the pieces should look like one sword, but in the Hierarchy they are still three separate GameObjects. Moving one piece at this point will not move the others.

Understanding Object Parenting
For the first arrangement, use the hilt as the parent. The guard and blade will then have a position, rotation, and scale relative to the hilt, so a Transform change to the hilt will carry the other pieces with it.
In the Hierarchy, drag the guard and blade onto the hilt. Both should appear indented beneath it.

Try moving, rotating, or scaling the hilt. The guard and blade should follow, so you can manipulate the whole sword by selecting the hilt alone.

To try the other arrangement, unparent the guard and blade first. In the Hierarchy, drag each one out from under the hilt.

Using an Empty GameObject as a Container
The hilt works as a parent, but an empty GameObject lets you control the sword without making one of its visible parts the root. It also lets you choose where the sword turns as a group. That point is called the pivot point.
Right-click in the Hierarchy and select Create Empty to add the container.

Name the new GameObject Sword and check that its Position is set to (0, 0, 0).

Drag the hilt, guard, and blade onto Sword in the Hierarchy so each part is a child of the empty GameObject.

Select Sword and try moving, rotating, or scaling it. All three cubes should transform together, even though none of them is the parent of another.

The Advantage of a Custom Pivot Point
The origin of the Sword parent, which you placed at (0, 0, 0), is the pivot for the group. In this setup the pivot is at the base of the hilt. To change where the sword turns, leave the parent where it is and adjust the parts around it.

Select all three children together and move them up or down. This shifts the assembled sword relative to its parent without changing how the three pieces line up with each other.

For example, shift them until the parent’s pivot lines up with the middle of the blade, a placement you might want for an animation or game mechanic. Rotate Sword to check the result: the pieces still turn together, but they now turn around the middle of the blade instead of the base of the hilt.

The parent stays in place while you adjust the children, so you can set the pivot for the group without rebuilding the model.
Work With Materials and Prefabs
Materials – Part 1
What Is a Material?
A material tells Unity how to draw an object’s surface. The same sphere can look like polished metal, matte plastic, or colored glass depending on the material you give it. Here are the properties that shape that appearance:
- Color: Sets the underlying color of the surface.
- Texture: Adds an image to the surface.
- Roughness/Smoothness: Gives the surface a matte or reflective finish.
- Metallic: Controls how much the surface looks and responds like metal.
- Light Interaction: Determines how the surface responds to the lights in the scene.

Creating a Material in Unity
Unity stores materials as assets in the Project window, alongside other project files such as scripts, scenes, textures, and models.

In the Project window, open the folder where you want to keep your material. Right-click inside the window and choose Create > Material from the context menu.

The new asset appears in that folder, ready to name. Give it a recognizable name such as TestMaterial so you can find it when you assign it to an object.

Select the asset to open its settings in the Inspector. At the bottom, a preview shows how the material looks on a sample mesh, before you apply it to anything in the scene.

Applying a Material to a Game Object
Start with an object that has a 3D mesh, such as a sphere, a cube, or a custom 3D model. New 3D objects use a gray material by default. You can replace it with your own, but cameras and lights do not have a mesh you can apply a material to.
Use whichever of these three methods is most convenient for the object you want to update.
Drag and Drop onto the Object
Find the material asset in the Project window, then drag it over the object in the Scene view and drop it directly onto the mesh.

Drag and Drop into the Inspector
Choose the object in the Hierarchy to open its Inspector. Under Mesh Renderer, find the Materials property and drop the asset from the Project window into its material slot.

Select from the Picker
With the object selected, go to the Mesh Renderer in the Inspector and click the small circle beside the slot under Materials.

The picker lists the materials in your project. Choose the one you want to assign it without dragging anything from the Project window.

Modifying Material Properties
Now select the material asset itself in the Project window. Use the settings in its Inspector to change the color, texture, or finish.
Base Map
The Base Map has controls for both color and texture. To change the tint, click the color swatch and choose a color in the picker.


To use an image as the surface texture, assign it in the field beside the color control.

Metallic
Move the Metallic slider to change how much the surface resembles metal.

Compare the ends of the slider: 0 gives you a non-metallic surface, and 1 makes it fully metallic.

Smoothness
Use the Smoothness slider to control how reflective the finish looks.

At 0, the surface looks rough and matte. At 1, it looks smooth and reflects its surroundings like a mirror.

Creating a Transparent Material
Changing the color does not make a material see-through by itself. Unity materials start out opaque, so for glass or a translucent gem, begin by changing the surface type.
Select the material asset and find Surface Type in the Inspector. Change it from Opaque to Transparent.

Next, click the color swatch beside Base Map to bring up the color picker.

Find the A slider, which stands for alpha. Lower it until you can see through the object. The lower the value, the more transparent the material becomes.

Challenge
Try making three spheres with distinct finishes. Use the Inspector settings to get each of these results:
- A red sphere with a highly reflective, metallic surface.
- A blue sphere with a very rough, non-metallic finish.
- A green sphere you can partially see through.

Start with the Base Map colors, then experiment with Metallic, Smoothness, and alpha. The walkthrough below shows how to set up the spheres and compare their finishes.
Materials – Part 2
Put the three spheres in the same scene so you can see the contrast between the shiny red finish, the matte blue finish, and the translucent green surface.

Setting Up the Scene
Choose 3D Object > Sphere from the menu to create the first object. You will use it as the center sphere and as the starting point for two copies.

Set the sphere’s X, Y, and Z position values to 0 in the Inspector so it sits at the center of the scene.

With the sphere selected, press Ctrl + D (Cmd + D on Mac). Hold Ctrl as you drag the duplicate to one side. Holding the key lets you snap the sphere to the grid as you move it.

Duplicate a sphere again and drag the new copy to the other side of the center sphere, using the same grid snapping method. You should see three spheres lined up in a row.

Creating a Reflective Red Material
For the first sphere, aim for a glossy surface like polished plastic or metal. In the Project window, right-click and choose Create > Material.

Name the asset Red. Drag it from the Project window and drop it onto the first sphere in the Scene view.

Select the sphere and find its material settings in the Inspector. Open the Base Map color picker by clicking the swatch, then choose a shade of red.

Increase Smoothness to 1 to give the red surface a reflective finish.

Look at the sphere in the Scene view. You should see the skybox reflected on its surface.

Creating a Rough Blue Material
Use the center sphere to contrast that glossy finish with a matte one. Create another material, name it Blue, and drag it onto the center sphere.

In the Inspector, choose a shade of blue in the Base Map color picker. Then drag Smoothness all the way down to 0 for a rough finish.

Compare the two spheres. The blue one has a solid, matte appearance rather than the red sphere’s visible reflections.

Creating a Translucent Green Material
For the remaining sphere, aim for the look of colored glass. Create an asset named Green and apply it to that sphere.

In the material’s Inspector settings, switch Surface Type from Opaque to Transparent so you can use alpha to make the surface see-through.

Open the Base Map color picker and set the color to green. Bring the Alpha (A) slider down to about halfway so the sphere keeps its green tint but becomes partially see-through.

Set Smoothness to 0 to make the transparency easier to see.

Move the camera until another sphere is behind the green one. You should be able to see it through the green surface.

Organizing Your Project
Give the three assets a shared home so you can find them as the project grows. Right-click in the Project window and choose Create > Folder.

Name the folder Materials. Select the Red, Blue, and Green assets in the Project window and drag them into it.

Open the Materials folder to check that all three assets are together.

Conclusion and Further Practice
Use the three spheres to compare how color, Smoothness, and the other settings work together. Try changing one property at a time to see how it affects the finish. To try a texture, click the small circle next to the Base Map texture field and choose an image.
Prefabs
Materials let you reuse a surface finish. To reuse a whole GameObject, save it as a Prefab asset in the Project window. Each copy you create from that asset is an instance. To see why that matters, start with a tree built from two GameObjects.
Creating a Base GameObject
Start with the trunk. Right-click in the Hierarchy and choose 3D Object > Cylinder to add a cylinder to the scene.

Use 3D Object > Sphere to add the sphere that will form the leaves.

In the Hierarchy, rename the cylinder Trunk and the sphere Leaves so you can tell the two parts apart.

In the Inspector, set both objects’ positions to (0, 0, 0). This gives you a common starting point before you arrange them.

Move Leaves up above Trunk and adjust the sphere’s scale until the two shapes look like a tree.

Use the Project window to create two materials so you can give the trunk and leaves different colors.

Name the material for the trunk Bark and the material for the sphere Leaves.

Select Bark and use its Base Map color picker to give it a brown tint.

Select the Leaves material and set its Base Map color to green.

In the Scene view, drag Bark onto the cylinder and Leaves onto the sphere. You should now have a brown trunk and a green canopy.

Choose GameObject > Create Empty and name the new object Tree. It will act as the parent for both pieces.

In the Inspector, set the position of Tree to (0, 0, 0).

In the Hierarchy, drag Trunk and Leaves onto Tree to make them children of the parent object. You can now move, rotate, or scale Tree to transform both parts together.

The Problem with Simple Duplication
If you wanted to fill a level with trees, you could duplicate the Tree GameObject and move the copies around the scene.

The drawback appears when you change the design. If you decide to make the leaves larger, you have to make the same edit to each duplicate by hand. With hundreds or thousands of trees, that takes time and makes it easy to miss a copy.

Creating and Using a Prefab
Make the tree a Prefab so its instances share one template. Select the parent Tree GameObject in the Hierarchy, then drag it into the Project window.

A new asset called Tree appears in the Project window with a blue cube icon. That is the reusable Prefab.

Look back at the Hierarchy. The original Tree and its children now have blue names, marking the tree in the scene as an instance of the Prefab.

Editing a Prefab
To change the design for all instances at once, work on the Prefab asset instead of one tree in the scene. Double-click Tree in the Project window to open it in the Prefab Editor. There you can edit the Prefab’s GameObjects as you would in the scene.

Select Leaves and move it down slightly. Duplicate it, position the copy above the original, and reduce the copy’s scale. The two spheres form a layered canopy.

Save the change with Ctrl + S or File > Save.

Click the back arrow in the upper-left corner of the Hierarchy to leave the Prefab Editor and return to the main scene.

The trees linked to the Prefab now show the new canopy without you having to edit each one in the scene.

Instance Overrides
Sometimes you want one tree to look different without changing the rest. Select one tree instance in the scene and try scaling its leaves.

That local change is an override. It belongs to the selected tree, so it does not alter the Prefab asset or the other instances.
- Editing the Prefab asset updates the shared design. Instances pick up the change unless they have an override for that property.
- Editing an instance in the scene changes just that copy.
Common Use Cases for Prefabs
The same workflow applies whenever you need several objects to share a design or want to reuse an object across levels:
- Environment Assets: Place copies of trees, rocks, or buildings throughout a level.
- Enemies: Make one template for an enemy type and spawn it multiple times during the game.
- Projectiles: Reuse a bullet or other projectile while keeping its behavior and appearance in one Prefab.
- Player Characters: Keep the player as a Prefab so you can create an instance at the start of each level.
Test Lighting and Physics
Lights
The Directional Light
Look for the Directional Light GameObject in the Hierarchy. A new Unity scene typically includes one by default. It acts like the sun, lighting the whole scene from the same direction.

Select the Directional Light, then look at the rays that appear in the Scene view. They show which way the light is shining.

With the light still selected, find its Light component in the Inspector. This is where Unity groups the settings for the light itself.

Press E to switch to the Rotate tool, then rotate the light while watching the shadows. A low angle stretches the shadows for a sunrise or sunset effect. Turn the light away from the scene to see how it looks without direct sunlight, as at night.

Modifying Light Properties
Rotation changes where the light comes from. Use the Light component in the Inspector to change its type, color, or brightness.
- Type: Open this dropdown to see the available kinds of light. The default sun uses Directional.

- Color: Try a pale yellow for sunlight, blue for a moonlit scene, or red for an alert. Watch how the same objects can look different without moving the light.


- Intensity: This controls how bright the light is. It typically starts at 1. Raise the value and compare the result with the original brightness.


Working with Shadows
Shadows help show depth, but rendering them comes at a performance cost. Compare these three options in the Directional Light’s Light component and look at the edges of the shadows in the scene.
- No Shadows: This light stops casting shadows. Turning them off can significantly improve performance.

- Hard Shadows: Look for sharp edges that can sometimes appear jagged. Hard shadows cost less to render than soft shadows.

- Soft Shadows: The edges blur for a more natural look. This is the most expensive of the three options to render.

Other Light Types
To add another kind of light, right-click in the Hierarchy, open Light, and choose a light type from the menu.

To see what the new light does on its own, temporarily turn off the other lights. For the Directional Light, select its GameObject and clear the checkbox beside its name at the top of the Inspector.

The Point Light
A Point Light shines outward in every direction from one position. Use it for a candle, a light bulb, or a glowing magical orb.
- Range: Select the light and look for the sphere around it in the Scene view. Changing Range adjusts the size of that sphere. Anything outside it remains unlit by the Point Light, no matter how high you set its intensity.


- Intensity and Color: Adjust the brightness and tint just as you did with the Directional Light. The changes affect the light within the sphere.


- Shadow Type: Use this setting to choose whether the Point Light casts shadows and how those shadows look.

The Spotlight
A Spotlight also shines from a single point, but it sends light in one direction in a cone. That makes it useful for flashlights, car headlights, and stage lighting.
- Spot Angle: Move the slider to widen or narrow the cone. To make the same adjustment in the Scene view, drag the handles on the cone’s wireframe.


- Range: Set how far the cone reaches. Where Spot Angle changes the spread of the beam, Range changes its reach, just as it does for a Point Light.

Once the cone covers the area you want to light, use the color, intensity, and shadow settings to adjust how that area looks.

Conclusion
Choose a Directional Light for sun-like illumination across the scene, a Point Light for a glow around one spot, or a Spotlight for a beam aimed at a specific area. Compare the results with the other lights switched off so you can see what each one contributes.
Physics
Once you can see the objects in the scene, test how they move. The first goal is to make a ball fall under gravity and stop at the floor.
What Is the Physics System?
Unity’s physics system simulates how GameObjects move under forces and interact when they make contact. The same system can support gameplay such as:
- Objects dropping under gravity.
- Projectiles traveling in an arc.
- Characters bumping into walls and walking up slopes.
- Players pushing crates or moving other objects.
For the first test, use a flat plane as the floor and position a sphere above it as the ball. Leave a gap so you can see the sphere fall once gravity is working.

Adding Physics with the Rigidbody Component
Press Play before adding any components. The sphere stays where you placed it. Its position, rotation, and scale describe its transform, but they don’t make the sphere fall or move in response to a collision.

Stop Play Mode. Select the sphere in the Hierarchy or the Scene view so you can add a Rigidbody to it.

With the sphere selected, go to the bottom of the Inspector and click Add Component.

Search for Rigidbody and select it from the results. You can also open the Physics category and select Rigidbody from that list. The new component appears in the sphere’s Inspector.


Press Play again and compare the result with the first run. Unity now applies gravity to the sphere through its Rigidbody, so the ball drops from its starting position and lands on the floor.

The Role of Colliders
The Rigidbody lets gravity move the ball, but the floor’s Mesh Collider is what gives it a surface to land on. A Collider defines the shape Unity uses to detect contact. When the falling ball meets the floor, Unity uses the colliders to work out how the objects interact instead of letting the sphere pass through the plane.

Exploring Rigidbody Properties
Select the sphere and look at its Rigidbody settings in the Inspector. Each setting affects a different part of the ball’s motion:
- Mass: Sets how heavy the object is. A heavier object takes more force to move.
- Linear Drag: Acts like air resistance against movement. Increase it to make the object slow down faster.
- Angular Drag: Acts like air resistance against rotation. Increase it to slow the object’s spin so it doesn’t keep spinning indefinitely.
- Use Gravity: Clear this checkbox if the object should not fall under the scene’s gravity, such as for an object floating in a game set in space.

Creating Dynamic Interactions
Stop Play Mode and swap a flat landing for a sloped one. Add a Cube GameObject, then scale and rotate it to make a ramp. Keep the sphere’s Rigidbody so it can fall onto the ramp and interact with the surface.

Position the sphere above the ramp and press Play. Watch for three stages: the ball drops onto the ramp, rolls along the slope, and falls off the edge.

Stop Play Mode and duplicate the sphere several times above the ramp. Run the scene again to see the spheres fall, roll down the ramp, and collide with one another.

A Note On Editing in Play Mode
You can select GameObjects and change their Inspector properties while the scene runs. This is useful for trying out a setting, but changes you make in Play Mode are temporary. When you stop the scene, the properties return to their values from before you pressed Play. If you want to keep an adjustment, make it again after you exit Play Mode.
Conclusion
Use the ball test to check two things separately. The Rigidbody makes the sphere respond to gravity and other forces. The colliders define where it makes contact, whether it’s landing on the floor, rolling down the ramp, or bumping into another sphere.
Write Your First C# Script in Unity
Intro to Scripting
Start with a script that makes a cube print a message. That gives you a simple way to check that Unity is running your code before you use scripts for gameplay.
What Is a Script?
A script is a text file that contains code. When you attach it to a GameObject in Unity, it appears as a component. A Light, Camera, or Rigidbody component gives an object a particular capability; a script lets you define a component with behavior of your own.
Creating Your First Script
In Unity, right-click inside the Project window and choose Create > MonoBehaviour Script from the context menu.

When Unity creates the file and prompts for a name, type MyFirstScript and press Enter.

The C# Language and Visual Studio
Unity scripts are primarily written in C# (pronounced “C-sharp”). Look for the C# symbol on the script icon in the Project window.
Double-click MyFirstScript to open it in your code editor. With a standard Unity installation, that editor is typically Visual Studio.

Unlike a plain text editor such as Notepad, Visual Studio gives you two useful tools as you write:
- Syntax highlighting: Colors distinguish different parts of the code so you can read it more easily.
- IntelliSense: Suggestions appear as you type, helping you complete code faster and avoid mistakes.
Understanding the Default Script
Unity generates this starter code when you create the script:
using UnityEngine;
public class MyFirstScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}Find Start() in the generated file. Unity calls it automatically just before the first frame update, so a statement placed between its opening { and closing } runs once when the game begins. That makes it a useful place to print a test message.
Writing Your First Line of Code
Between the braces of Start(), type this statement:
Debug.Log("Hello!");Debug.Log()prints a message to Unity’s Console. You can use it to check whether your code ran or to see what value it produced.- The text inside the parentheses,
"Hello!", is the message to print. The double quotation marks tell C# that it is text. - The semicolon (
;) marks the end of the statement.
Check that the line sits inside the braces, as shown here:
void Start()
{
Debug.Log("Hello!");
}Press Ctrl+S or click the save icon in Visual Studio.
Attaching and Running the Script
Switch back to the Unity editor. Give Unity a moment to compile the saved script, converting your code into a form it can run.

The script needs a GameObject to run on. Add a cube to the scene with GameObject > 3D Object > Cube, then locate it in the Hierarchy.

Select the Cube to see its components in the Inspector. You can attach the script in either of two ways:
- Click Add Component at the bottom of the Inspector, search for
MyFirstScript, and select the matching result.

- Or drag the
MyFirstScriptfile from the Project window and drop it directly onto the Cube’s Inspector.

Before running the scene, check that My First Script appears in the Cube’s component list.

Click Play at the top of the editor and look for Hello! in the Console at the bottom of the screen. If the Console isn’t visible, open it from Window > General > Console. The message confirms that Unity ran the code inside Start().

Variables – Part 1
A message can show that your code ran. A variable lets the code keep track of something that can change while the game runs, such as the player’s health.

For instance, you could reduce the value stored in PlayerHealth each time the player takes damage. You could also read that value to check whether health has reached zero or less and the player has been defeated.
Creating Your First Variable
Open MyFirstScript again in Visual Studio and work between the braces of Start(). That way, the examples run once when you press Play. A variable can store a whole number, a decimal number, or text, depending on how you declare it.
To declare a variable with a starting value, write these three parts:
- Type: The kind of data the variable can store, such as a whole number or text.
- Name: The identifier you use to refer to the variable later.
- Initial value: The data the variable holds when you first create it.
For the health example, write int for an integer (a whole number), followed by the name health. Use = to assign the starting value 100 and finish the declaration with a semicolon.
void Start()
{
int health = 100;
}Visual Studio may put a green squiggle under health. This is a warning, not an error: the variable exists, but the code doesn’t read its value yet.
Using and Displaying a Variable
Pass health to Debug.Log() on the line after the declaration. Unlike the earlier "Hello!" message, the variable name goes inside the parentheses without quotes so the Console displays the value it holds.
void Start()
{
int health = 100;
Debug.Log(health);
}Save the script, return to Unity, and press Play. Look for 100 in the Console to confirm that the script read the variable’s initial value.

Order of Execution
The statements in this example run from top to bottom. Declare health before reading it. If you reverse those two lines, you get this error instead of a Console message:
void Start()
{
// This will cause an error!
Debug.Log(health);
int health = 100;
}Visual Studio underlines the problem in red and displays an error like “Cannot use local variable ‘health’ before it is declared.” At the point where Debug.Log(health) appears, the declaration below it isn’t available yet.

Changing a Variable’s Value
Once you’ve declared a variable, assign a new value by writing its name followed by = and the new value. Leave off int because you’re updating the existing variable, not declaring another one.
To see both values in the Console, arrange the statements inside Start() in this order:
- Declare
healthwith an initial value of100. - Pass
healthtoDebug.Log()to print the starting value. - Assign
50to the same variable. - Log
healthagain to print the updated value.
void Start()
{
int health = 100;
Debug.Log(health);
health = 50;
Debug.Log(health);
}Save the script and run the scene in Unity again. The Console should show 100 first and then 50. Each call prints what health holds at that point in the script.

Variables – Part 2
Health was a whole number, but not every value fits in an int. Choose a type according to what the variable represents: a decimal value, a piece of text, or a true-or-false state.
Floating-Point Numbers
A value such as 1, 256, or 1000000 fits in an integer. A movement speed of 5.25 needs a type that can represent the fractional part. For that, use a float, short for floating-point number.
Put float before the variable name and add an f to the end of the decimal value. The suffix tells C# to treat that number as a float.
float moveSpeed = 5.25f;
The name moveSpeed uses a convention called camelCase: start with a lowercase word and capitalize the first letter of each later word. Names like moveSpeed and thisItemName are easier to read this way. You can’t add spaces between the words because C# uses spaces to separate parts of a statement.
To check the starting speed, pass moveSpeed to the same logging function you used for health. The Console should show 5.25.
Debug.Log(moveSpeed);

To change the speed later, assign a different float without repeating the type. A float can also hold a value with more decimal places, such as 5.5024f.
moveSpeed = 5.5024f;
Strings
Use a string for a sequence of characters such as a player’s name. Put the text between double quotation marks when you assign it:
string playerName = "Bob";
When the name changes from Bob to Tim, give playerName a new quoted value:
playerName = "Tim";
C# is strongly typed, so the type of a variable determines what you can assign to it. The next example deliberately tries to put the integer 5 into a string variable:
// This will cause an error! playerName = 5;
Visual Studio highlights the assignment and reports that it cannot implicitly convert int to string. If you try the line yourself, remove it after checking the error so it doesn’t interfere with the next example.

Booleans
Use a boolean, declared with bool, when a piece of game state has only two possibilities. A door can be open or not, and a game can be over or not. The two values are true and false.
Start with gameOver set to false:
bool gameOver = false;
When the game is over, assign true. Both true and false are C# keywords, so write them in lowercase.
gameOver = true;
Summary of Data Types
Use these four common types as a starting point when deciding how to store a value:
intstores a whole number such as100.floatstores a number with a fractional part. Write decimal values with anfsuffix, as in5.25f.stringstores text. Put the text in double quotes, as in"Bob".boolstores a state that is eithertrueorfalse.
Challenge
Describe one country with four variables. Use a different type for each value:
- The country’s name.
- The size of its population.
- Its highest altitude.
- Whether it’s landlocked.
Look up the figures for a real country or make up your own. Write the four declarations before comparing them with the solution.
Variables – Part 3
Challenge Solution
Australia is the example here. Match each piece of information to the kind of value it needs to store:
- Country name: Use a
stringbecause the country’s name is text. - Population: Count people with an
int, since the count is a whole number. - Highest altitude: Use a
floatso the measurement can include a decimal part. - Landlocked status: Use a
boolbecause the country either is landlocked or isn’t.
Put the type before each name and use = to give each variable its starting value:
string countryName = "Australia"; int population = 27200000; float highestAltitude = 2280.5f; bool landlocked = false;
Understanding Comments
Look at the green line above Start() in Visual Studio. It begins with // and describes when Unity calls the function.

That line is a comment: it’s there for the person reading the code, not for the computer to execute. The compiler ignores it.
- Explain logic that might not be clear from the code alone.
- Leave a note or reminder for yourself or another reader.
- Temporarily disable a line during testing by turning it into a comment.
To write a single-line comment in C#, type two forward slashes (//). Anything after them on the same line is part of the comment. Try adding one above the four country variables:
// Challenge variables string countryName = "Australia"; int population = 27200000; float highestAltitude = 2280.5f; bool landlocked = false;
The line // Challenge variables labels the group for readers without changing how Unity runs the declarations below it.
Operators – Part 1
Using Operators for Addition
Instead of replacing a value outright, you can use the old value to calculate the new one. Try this with a player’s score. In your script, declare an integer named score and start it at zero:
int score = 0;
Suppose the player earns one point. The addition assignment operator (+=) takes the current score, adds the amount on the right, and stores the result back in score.
score += 1;
Since the score started at 0, adding 1 updates it to 1. Log the value after the addition to check it:
int score = 0; score += 1; Debug.Log(score);

Add another five points before logging. The second addition starts with the updated score of 1, so the Console should now show 6.
int score = 0; score += 1; score += 5; Debug.Log(score); // The console will now output 6
Use the addition operator (+) on its own to calculate a sum without changing either of the values you’re adding. Start with two integers, a and b:
int a = 5; int b = 2;
Add them together with + and store their sum in a third variable, c:
int c = a + b;
C# reads 5 from a and 2 from b, so c is 7. You can also use several additions in one expression, mixing variables and numbers as shown here:
int result = a + b + 2 + 1599;
The Importance of Execution Order
The addition works for the same reason that logging health worked earlier: the values are in place before you ask the code to read them. Declare and assign a and b before the statement that calculates c.
int a = 5; int b = 2; int c = a + b; // This works because a and b are already defined.
Move the calculation above those declarations and the compiler can no longer resolve either name at that point:
// This will cause an error! int c = a + b; int a = 5; int b = 2;
Visual Studio reports that the local variables a and b can’t be used before they’re declared. Move the calculation back below both declarations to fix it.

Operators – Part 2
The same two patterns apply when subtracting, multiplying, or dividing. You can update an existing value or use the result of a calculation somewhere else.
Subtraction
Use subtraction assignment (-=) to take two points away from the current score and store the result back in score:
// Subtraction score -= 2;
If the score was 6 before this statement, it is 4 afterward. To calculate a difference without changing the original value, use - in an expression. This example subtracts 3 from a and stores the result in b:
b = a - 3;
Multiplication
C# uses the asterisk (*) for multiplication. To multiply the current score by 5 and keep the result in score, use *=:
// Multiplication score *= 5;
Use * on its own to multiply two values in an expression. Here, b receives twice the value of c:
b = 2 * c;
Division
The forward slash (/) divides one value by another. Combine it with = to divide the current score by 2 and save the result back to score:
// Division score /= 2;
To use division as part of an expression instead, write / by itself. Here, the result of dividing c by 4 goes into b:
b = c / 4;
Operators with Other Data Types
These operations work with floats as well as integers. For example, multiply a jump height by 1.5f to increase it by 50 percent:
float jumpHeight = 5.7f; jumpHeight *= 1.5f;
With strings, + does something different. It joins the text on either side of the operator into one string, an operation called concatenation:
string message = "Hello " + " world";
Of the arithmetic operators shown here, only + works with strings: you can join them, but you can’t subtract, multiply, or divide them. None of these arithmetic operators apply to booleans, which represent true or false rather than quantities.
Challenge
Apply each operation in turn to the same variable. Use the compound assignment operators +=, *=, -=, and /= so each line starts with the result of the previous one.
- Declare an integer called
moneyand start it at10. - Add
5. - Double the current amount.
- Subtract
3. - Divide the remaining amount by
2.
Write the calculation before comparing your script with the solution.
Operators – Part 3
Challenge Solution: Manipulating a Variable
Open your script and give money its starting value of 10. You’ll update that same integer on each line, then log the final amount.
// Money challenge int money = 10;
Add five with +=. The variable now holds 15.
money += 5;
Double that amount with *= to get 30.
money *= 2;
Take three away with -=, leaving 27.
money -= 3;
Use /= to divide the remaining amount by two.
money /= 2;
Once all four operations have run, pass money to Debug.Log() so the Console shows the final value.
Debug.Log(money);
Check that your declaration, four updates, and log statement appear in this order:
// Money challenge int money = 10; money += 5; money *= 2; money -= 3; money /= 2; Debug.Log(money);
Save the script, go back to the Unity editor, and press Play. The Console should show 13.

Conditions – Part 1
Once you can update the player’s score, you can use it to decide what happens next. A condition evaluates to true or false, and that result determines whether a block of code runs.
Statements and Comparisons
Use a comparison operator to ask a question about two values. The equality operator (==) checks whether they’re the same. Unlike =, it compares values rather than assigning one.
5 == 5evaluates totruebecause both sides are5.3 == 7evaluates tofalsebecause3and7are different.
The ‘if’ Statement
Put a condition in an if statement to control when a block runs. If the condition is true, the program runs the statements inside the block. If it’s false, the program skips them.
Think of the spacebar as a condition for jumping. You don’t want the player to jump every time the code runs. You want the jump to happen only if the spacebar was pressed.
Implementing Conditions in Unity
Try a win condition in your script. Start with an integer called score set to 3:
int score = 3;
Below the declaration, write if followed by score == 10 in parentheses. Put the call to Debug.Log() between curly braces so the win message prints only when the score is exactly 10.
if(score == 10)
{
Debug.Log("Player has won!");
}Don’t put a semicolon after the condition. The if controls the block that follows it; the log statement inside the block is what ends in a semicolon.
Run the script with the score still set to 3. You won’t see a win message. The comparison is false, so Unity skips the log statement inside the braces.

Now change the starting score to 10 and leave the check as it is:
int score = 10;
if(score == 10)
{
Debug.Log("Player has won!");
}Run the script again. This time score == 10 is true, so the Console shows Player has won!.

Other Comparison Operators
When you want the opposite of equality, use !=, which means “not equal to.” This block logs a message for any score other than 10:
if(score != 10)
{
Debug.Log("Player does not have 10 score.");
}To compare a number against a limit rather than an exact match, switch to the example below. Start with health set to 50:
int health = 50;
The greater-than operator (>) is true when the value on the left is larger than the value on the right. If health is above zero, the player is still active:
if(health > 0)
{
Debug.Log("Player is still active.");
}The less-than operator (<) is true when the value on the left is smaller. With health stored as an integer, a value below 1 means the player has been defeated:
if(health < 1)
{
Debug.Log("Player has been defeated!");
}Add an equals sign to include the boundary value in the comparison:
>=means the value on the left is greater than or equal to the value on the right.<=means the value on the left is less than or equal to the value on the right.
The defeat check reads more directly with <=: the player is defeated when health is zero or below.
if(health <= 0)
{
Debug.Log("Player has been defeated!");
}Conditions – Part 2
Sometimes two comparisons can both be true, even though you only want one result. A score-to-grade example shows why the way you connect those checks matters.
The Problem with Multiple If Statements
Declare a variable to hold the numerical score you’ll grade:
int score = 75;
Start with two separate checks. Print A for a score of at least 90, and print B for a score of at least 70:
if (score >= 90)
{
Debug.Log("A");
}
if (score >= 70)
{
Debug.Log("B");
}At 95, the first check prints A. The second check still runs independently, and since 95 also meets the threshold of 70, it prints B as well. For one grade per score, the second check should run only if the first one fails.
Using ‘else If’ for Exclusive Conditions
Change the second if to else if to make it part of the same chain. The second condition is now checked only when the first is false.
if (score >= 90)
{
Debug.Log("A");
}
else if (score >= 70)
{
Debug.Log("B");
}With a score of 95, the first block prints A and Unity skips the rest of the chain. With a score of 75, Unity skips the first block, checks the next threshold, and prints B. Only the first matching block runs.
Chaining Multiple ‘else If’ Statements
You can add more else if blocks to the same chain. Put the C check after the checks for A and B, and set its threshold to 50:
if (score >= 90)
{
Debug.Log("A");
}
else if (score >= 70)
{
Debug.Log("B");
}
else if (score >= 50)
{
Debug.Log("C");
}If the score is 52, it misses the first two thresholds but meets the third, so the Console shows C.
The ‘else’ Statement as a Default Case
A score below 50 should get a D. Rather than write another comparison, add an else at the end of the chain. It takes no condition and runs only when none of the earlier conditions match.
if(score >= 90)
{
Debug.Log("A");
}
else if(score >= 70)
{
Debug.Log("B");
}
else if(score >= 50)
{
Debug.Log("C");
}
else
{
Debug.Log("D");
}Try a score of 20. It misses every threshold, so the final else block prints D.
Challenge
Use if and else to choose between two messages based on a piece of text:
- Declare a
stringvariable namedcountry. - Use
ifto check whethercountryequals"France". - If the strings match, log a message confirming that it’s France.
- Use
elseto log a different message if it isn’t France.
Conditions – Part 3
Challenge Solution: Checking Country
In your script, give the country string a starting value of "Germany". This will let you check that the else branch works.
string country = "Germany";
Compare country with "France" using ==. Put the confirmation message inside the if block and the alternative message inside else. You don’t need another comparison in the else block: if control reaches it, the strings didn’t match.
// Conditions challenge
string country = "Germany";
if(country == "France")
{
Debug.Log("This is France.");
}
else
{
Debug.Log("This is not France.");
}Testing in Unity
- Save the script.
- Switch back to the Unity editor.
- Wait for Unity to finish compiling the script.
- Click Play at the top of the editor.
Check the Console after the scene starts. If you kept the earlier checks in your script, their output appears first. Because country holds "Germany", the comparison with "France" is false. The new message should read This is not France.

Functions
A function gives a block of code a name so you can run it from more than one place. For example, a function could make the player jump or turn a light on or off.
Understanding Existing Functions
Your MonoBehaviour script already has two functions Unity calls for you:
Start()runs once when the script instance is first enabled, before its firstUpdate(). That’s why the examples inStart()run once when you press Play.Update()runs every frame. Use it for logic that needs to keep running, such as checking player input or moving an object.
using UnityEngine;
public class MyFirstScript : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
// Code here runs once at the start
}
// Update is called once per frame
void Update()
{
// Code here runs every frame
}
}The Structure of a Function
Read a function definition from its return type down through the code in its braces:
- Return type: The type of value the function gives back when it finishes. If it gives back no value, write
void, as inStart()andUpdate(). - Name: The identifier you’ll use to call the function.
- Parameters: The inputs listed inside the parentheses. If the function takes no inputs, leave the parentheses empty.
- Body: The statements between the curly braces that run when the function is called.
Creating and Calling Your First Function
Add LogToConsole() inside MyFirstScript, but outside the bodies of Start() and Update(). This function takes no inputs and gives back no value. Its only job is to print a message.
void LogToConsole ()
{
Debug.Log("This function has been called.");
}Save the script and press Play in Unity. You won’t see the new message yet. Defining LogToConsole() gives the statements a name, but it doesn’t run them. To run the body, call the function by name.

Put the call to LogToConsole() inside Start() to run it once when the scene starts:
void Start()
{
LogToConsole();
}Press Play again. Look for This function has been called. in the Console.

Now try calling LogToConsole() from Update() instead. The same function runs every frame, so you’ll see the Console fill with repeated messages:
void Update()
{
LogToConsole();
}
Functions with Parameters and Return Values
LogToConsole() always performs the same action. To reuse a calculation with different numbers, give the function parameters for its inputs and return the result. Add this function to your script:
float Add(float a, float b)
{
float sum = a + b;
return sum;
}floatbefore the name means the function returns a floating-point value.Addis the name you use to call the function.float aandfloat bare the two parameters, one for each input.- Inside the braces, the function adds
aandb, stores the answer insum, and usesreturnto give that value back to the caller.
In Start(), call Add() with two float values. Assign the returned value to number, then pass number to Debug.Log():
void Start()
{
float number = Add(2.5f, 3.77f);
Debug.Log(number);
}Think of Add(2.5f, 3.77f) in the assignment as the value it returns. The function adds 2.5 and 3.77, so when you run the script, the Console shows 6.27.

Try writing a function that multiplies or divides two numbers instead. Change the parameters or return type, then call the function and log the result to check what it returns.
Move a GameObject With Unity Vectors
Position, Movement, and Frame Rate
Earlier, you used the Inspector to move a cube by changing its X, Y, and Z values. Now you’ll do the same thing in C#: first place the cube at a specific point, then make it move continuously.
Unity’s Coordinate System
To locate a point in a 3D Unity scene, read the three axes together:
- X: left and right.
- Y: up and down.
- Z: forward and backward.

Together the three coordinates identify a point in 3D space. In a 2D game, you’ll typically work with X and Y.
Understanding Vectors
Select a GameObject and look at how its Transform groups three fields under each of Position, Rotation, and Scale. Focus on Position for these examples.

A Vector3 puts three floating-point values into one variable. The three numbers can describe a point in the scene or how far to move along each axis.
Using Vectors in Code
Return to the script you attached to the cube. Replace your current Start() example with this one. It creates a Vector3 but doesn’t move the cube yet:
void Start()
{
Vector3 newPosition = new Vector3(3, -2, 4);
}The numbers in newPosition correspond to X = 3, Y = -2, and Z = 4. To put the cube there, assign the vector to transform.position:
void Start()
{
Vector3 newPosition = new Vector3(3, -2, 4);
transform.position = newPosition;
}Save and press Play. As soon as Start() runs, the attached GameObject jumps to (3, -2, 4).

Moving GameObjects
To move the cube relative to its starting point, add to its current position rather than replacing it. Swap in this Start() example:
void Start()
{
Vector3 movement = new Vector3(1, 0, 0);
transform.position += movement;
}movement adds one unit on X and zero on Y and Z. When you press Play, the cube moves one unit to the right and stops because Start() only runs once.

Continuous Movement With Update
Remove the movement from Start() and replace the existing Update() method with this version so the same change happens once per frame:
void Update()
{
Vector3 movement = new Vector3(1, 0, 0);
transform.position += movement;
}
The cube moves quickly because every frame adds a whole unit. That also means it moves faster on a machine rendering more frames per second.
Frame-Rate Independent Movement
Instead of adding a whole unit each frame, multiply the movement vector by Time.deltaTime, the time elapsed since the previous frame. Short frames apply a smaller step; long frames apply a larger one.
void Update()
{
Vector3 movement = new Vector3(1, 0, 0) * Time.deltaTime;
transform.position += movement;
}Run this version and the cube moves at one unit per second along X rather than one unit per frame.

A Note on Vector Operations
If you use the vector only once, you can write it directly in the expression. To move down instead of right, replace Update() with this version, which subtracts movement along Y:
void Update()
{
transform.position -= new Vector3(0, 1, 0) * Time.deltaTime;
}
Press Play again. The cube now moves down at one unit per second. Compare the examples: changing the nonzero component changes the axis, while adding or subtracting changes the direction along it.
What You Can Now Do in Unity
The moving cube brings the tutorial full circle: the axes you first used to position a GameObject in the editor now control how it moves in code. Along the way, you practiced how to:
- Install Unity, create a 3D project, and navigate the Scene view.
- Transform and group GameObjects, then save a reusable Prefab.
- Change how objects look with materials and lighting, and test collisions with a Rigidbody.
- Write a C# script using variables, conditions, functions, and vectors.
Try changing which vector axis you use, then press Play to see how it changes the cube’s direction.
When you’re ready to put these skills to work in guided projects, continue with Zenva’s Unity Game Development Mini-Degree.
Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.







