Unity for Beginners: From Unity Hub to Your First C# Script

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.

Make a Complete Card Battler in Godot e1788415191322 - Unity for Beginners: From Unity Hub to Your First C# Script
FREE GODOT COURSE
LEARN GODOT, UNITY, UNREAL & MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

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.

image 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 2 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 3 - Unity for Beginners: From Unity Hub to Your First C# Script

Installation and Account Setup

Open the downloaded setup file.

image 4 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 5 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 5 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 6 - Unity for Beginners: From Unity Hub to Your First C# Script

Installing the Unity Editor

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

image 7 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 8 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 9 - Unity for Beginners: From Unity Hub to Your First C# Script

Accept the terms and click Install to confirm.

image 10 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 11 - Unity for Beginners: From Unity Hub to Your First C# Script

Start a Project in the Hub

Creating a New Project

Check that your editor version now appears under Installs.

image 12 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 13 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 14 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 15 - Unity for Beginners: From Unity Hub to Your First C# Script

Understanding Project Templates

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

image 16 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 16 - Unity for Beginners: From Unity Hub to Your First C# Script

Fill in the fields on the right:

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

image 16 - Unity for Beginners: From Unity Hub to Your First C# Script

Launching the Editor

Click the blue Create Project button.

image 17 - Unity for Beginners: From Unity Hub to Your First C# Script

Accept the software terms if Unity asks again.

image 18 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 18 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 18 2 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 18 3 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 18 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 19 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 20 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 22 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 21 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 23 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 24 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 25 - Unity for Beginners: From Unity Hub to Your First C# Script

Select a few GameObjects in the Hierarchy and compare what the Inspector shows. Look for these components:

  1. 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.
  2. 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.
  3. 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.

image 26 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 27 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 28 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 29 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 30 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 31 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 32 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 32 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 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.

image 32 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 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.

image 33 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 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.

image 34 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 34 2 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 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.

image 34 3 - Unity for Beginners: From Unity Hub to Your First C# Script

To change height while flying, keep the right mouse button held and use these keys:

  • E: Fly up.
  • Q: Fly down.

image 34 4 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 36 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 36 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 35 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 34 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 36 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 37 - Unity for Beginners: From Unity Hub to Your First C# Script

image 38 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 39 - Unity for Beginners: From Unity Hub to Your First C# Script

  1. 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.

image 39 - Unity for Beginners: From Unity Hub to Your First C# Script

  1. 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.

image 40 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 40 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 41 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 42 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 43 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 44 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 45 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 46 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 47 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 47 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 49 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 50 - Unity for Beginners: From Unity Hub to Your First C# Script

image 51 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 52 - Unity for Beginners: From Unity Hub to Your First C# Script

image 53 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 54 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 55 - Unity for Beginners: From Unity Hub to Your First C# Script

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).

image 56 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 57 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 58 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 59 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 60 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 70 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 62 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 63 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 64 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 65 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 66 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 67 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 68 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 69 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 72 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 72 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 73 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 74 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 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.

image 75 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 76 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 77 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 61 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 78 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 79 - Unity for Beginners: From Unity Hub to Your First C# Script

Click Local to switch the setting to Global.

image 80 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 81 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 82 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 82 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 83 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 71 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 84 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 85 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 86 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 87 - Unity for Beginners: From Unity Hub to Your First C# Script

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).

image 88 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 89 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 2 doubles that dimension.

image 90 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 0.5 reduces that dimension to half its original size.

image 91 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 92 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

  1. Add a few primitive GameObjects. For example, use cubes for the torso and limbs and a sphere for the head.
  2. Arrange the shapes so the figure has a head, a body, two arms, and two legs.
  3. 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.

image 93 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 93 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 94 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 95 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 96 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 107 - Unity for Beginners: From Unity Hub to Your First C# Script

Adding the Legs

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

image 97 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 98 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 99 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 100 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 101 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 102 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 103 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 104 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 105 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 106 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 108 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 112 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 109 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 110 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 111 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 113 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 114 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 115 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 116 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 117 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 118 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 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.

image 119 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 120 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 120 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 122 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 121 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 123 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 124 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 125 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 126 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 127 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 128 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 129 - Unity for Beginners: From Unity Hub to Your First C# Script

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)

image 130 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 131 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 132 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 133 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 134 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 135 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 136 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 137 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 138 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 139 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 140 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 141 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 142 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 143 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 144 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 145 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 146 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 147 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 148 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 149 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 150 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 151 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 152 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 152 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 153 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 154 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 155 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 164 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 165 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 156 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 157 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 158 - Unity for Beginners: From Unity Hub to Your First C# Script

image 159 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 157 - Unity for Beginners: From Unity Hub to Your First C# Script

Metallic

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

image 160 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 161 - Unity for Beginners: From Unity Hub to Your First C# Script

Smoothness

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

image 162 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 163 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 166 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 167 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 168 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 169 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 169 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 170 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 171 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 172 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 173 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 174 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 175 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 176 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 177 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 178 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 179 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 179 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 180 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 181 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 182 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 183 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 184 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 185 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 186 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 187 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 188 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 189 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 190 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 198 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 191 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 192 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 193 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 195 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 194 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 196 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 197 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 199 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 200 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 201 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 202 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 202 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 202 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 203 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 204 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 205 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 205 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 206 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 207 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 208 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 208 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 208 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 209 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 210 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 211 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 212 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 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.

image 213 - Unity for Beginners: From Unity Hub to Your First C# Script

image 214 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 215 - Unity for Beginners: From Unity Hub to Your First C# Script

image 216 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 216 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 217 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 216 - Unity for Beginners: From Unity Hub to Your First C# Script

Other Light Types

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

image 218 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 219 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 220 - Unity for Beginners: From Unity Hub to Your First C# Script

image 221 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 221 - Unity for Beginners: From Unity Hub to Your First C# Script

image 222 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 222 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 223 - Unity for Beginners: From Unity Hub to Your First C# Script

image 224 - Unity for Beginners: From Unity Hub to Your First C# Script

  • 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.

image 224 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 225 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 225 1 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 225 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 226 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 227 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 228 - Unity for Beginners: From Unity Hub to Your First C# Script

image 229 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 230 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 232 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 231 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 233 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 234 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 235 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 236 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 237 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 238 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 238 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 239 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 240 - Unity for Beginners: From Unity Hub to Your First C# Script

  • Or drag the MyFirstScript file from the Project window and drop it directly onto the Cube’s Inspector.

image 241 - Unity for Beginners: From Unity Hub to Your First C# Script

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

image 242 - Unity for Beginners: From Unity Hub to Your First C# Script

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().

image 243 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 244 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 245 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 246 - Unity for Beginners: From Unity Hub to Your First C# Script

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:

  1. Declare health with an initial value of 100.
  2. Pass health to Debug.Log() to print the starting value.
  3. Assign 50 to the same variable.
  4. Log health again 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.

image 247 - Unity for Beginners: From Unity Hub to Your First C# 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);

image 248 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 250 - Unity for Beginners: From Unity Hub to Your First C# Script

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:

  • int stores a whole number such as 100.
  • float stores a number with a fractional part. Write decimal values with an f suffix, as in 5.25f.
  • string stores text. Put the text in double quotes, as in "Bob".
  • bool stores a state that is either true or false.

Challenge

Describe one country with four variables. Use a different type for each value:

  1. The country’s name.
  2. The size of its population.
  3. Its highest altitude.
  4. 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 string because the country’s name is text.
  • Population: Count people with an int, since the count is a whole number.
  • Highest altitude: Use a float so the measurement can include a decimal part.
  • Landlocked status: Use a bool because 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.

image 251 - Unity for Beginners: From Unity Hub to Your First C# Script

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);

image 251 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 252 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

  1. Declare an integer called money and start it at 10.
  2. Add 5.
  3. Double the current amount.
  4. Subtract 3.
  5. 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.

image 253 - Unity for Beginners: From Unity Hub to Your First C# Script

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 == 5 evaluates to true because both sides are 5.
  • 3 == 7 evaluates to false because 3 and 7 are 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.

image 254 - Unity for Beginners: From Unity Hub to Your First C# Script

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!.

image 255 - Unity for Beginners: From Unity Hub to Your First C# Script

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 string variable named country.
  • Use if to check whether country equals "France".
  • If the strings match, log a message confirming that it’s France.
  • Use else to 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

  1. Save the script.
  2. Switch back to the Unity editor.
  3. Wait for Unity to finish compiling the script.
  4. 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.

image 256 - Unity for Beginners: From Unity Hub to Your First C# Script

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 first Update(). That’s why the examples in Start() 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:

  1. Return type: The type of value the function gives back when it finishes. If it gives back no value, write void, as in Start() and Update().
  2. Name: The identifier you’ll use to call the function.
  3. Parameters: The inputs listed inside the parentheses. If the function takes no inputs, leave the parentheses empty.
  4. 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.

image 254 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 257 - Unity for Beginners: From Unity Hub to Your First C# Script

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();
}

image 258 - Unity for Beginners: From Unity Hub to Your First C# Script

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;
}
  • float before the name means the function returns a floating-point value.
  • Add is the name you use to call the function.
  • float a and float b are the two parameters, one for each input.
  • Inside the braces, the function adds a and b, stores the answer in sum, and uses return to 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.

image 259 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 56 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 260 - Unity for Beginners: From Unity Hub to Your First C# Script

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).

image 261 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 262 - Unity for Beginners: From Unity Hub to Your First C# Script

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;
}

image 264 - Unity for Beginners: From Unity Hub to Your First C# Script

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.

image 265 - Unity for Beginners: From Unity Hub to Your First C# Script

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;
}

image 266 - Unity for Beginners: From Unity Hub to Your First C# Script

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!

FREE COURSES
Python Blog Image - Unity for Beginners: From Unity Hub to Your First C# Script

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