How to Create a Simple 3D Game in Unity for PC

 

How to Create a Simple 3D Game in Unity for PC

Welcome to the exciting world of game development! If you've ever dreamed of building your own video games but felt intimidated by the process, you've come to the right place. This comprehensive, step-by-step guide is designed for absolute beginners and will walk you through every stage of creating your very first simple 3D game in Unity for PC. By the end of this tutorial, you will have a playable game and a strong foundational knowledge of the Unity engine that will empower you to continue your journey as a game developer.

Unity is one of the most popular and powerful game engines in the world, used to create everything from blockbuster AAA titles to beloved indie gems. Its intuitive interface, extensive documentation, and vibrant community make it the perfect starting point. In this guide, we'll cover everything from installing the software to scripting player movement, creating a level, implementing game mechanics, and finally, building your game into an executable file you can share with friends. We will focus on creating a simple 3D game where a player navigates a level, collects items, and reaches a goal. No prior coding or game development experience is required. Let's get started!

Chapter 1: Setting Up Your Development Environment

Before we can build our world, we need to lay the groundwork by installing the necessary tools. This involves downloading Unity Hub, the Unity Editor, and a code editor.

Downloading and Installing Unity Hub

Your journey begins with Unity Hub, a management tool that allows you to manage all your Unity projects and installations. It simplifies the process of downloading different versions of the Unity Editor, which is crucial as you work on various projects over time.

  1. Navigate to the Unity Website: Open your web browser and go to the official Unity download page at unity.com/download.

  2. Download Unity Hub: Click the "Download Unity Hub" button. This will download the installer for your operating system (Windows or macOS).

  3. Run the Installer: Once the download is complete, run the installer. Follow the on-screen prompts, accepting the license agreement and choosing an installation location.

  4. Sign In or Create an Account: After installation, launch Unity Hub. You will be prompted to sign in with a Unity ID. If you don't have one, creating one is free and only takes a few minutes.

Installing the Unity Editor

With Unity Hub installed, it's time to get the actual game engine—the Unity Editor. It's highly recommended to use a Long-Term Support (LTS) version, as these are the most stable and well-supported releases.

  1. Open the "Installs" Tab: In Unity Hub, navigate to the "Installs" tab on the left-hand side.

  2. Click "Install Editor": Press the blue "Install Editor" button.

  3. Choose an LTS Version: You'll see a list of available Editor versions. We recommend selecting the latest LTS release (e.g., "2022.3.x" or a newer LTS version). These are optimized for projects that you plan to release.

  4. Select Modules: During installation, Unity will ask which modules you want to add. For PC game development, ensure that "Microsoft Visual Studio Community [version]" is checked. This is the code editor (or Integrated Development Environment - IDE) that we will use to write our C# scripts. If you're on a Mac, it will integrate with Visual Studio for Mac. You can also add build support for other platforms like Android or WebGL later if you wish.

  5. Begin Installation: Click "Install." Unity Hub will now download and install the chosen Editor version and Visual Studio. This may take some time depending on your internet connection.

Creating Your First 3D Project

Once the Editor is installed, you are ready to create the project for your first game.

  1. Go to the "Projects" Tab: In Unity Hub, select the "Projects" tab.

  2. Click "New Project": Click the "New project" button in the top-right corner.

  3. Select the "3D Core" Template: A new window will appear with various project templates. For our purposes, select the "3D Core" template. This provides a clean slate optimized for creating a 3D game.

  4. Configure Project Settings: On the right, you will need to name your project (e.g., "MyFirst3DGame") and choose a location on your computer to save it.

  5. Create the Project: Click the "Create project" button. Unity will now create all the necessary files and open the Unity Editor for the first time. This initial launch can be slow as it imports all the required assets, so be patient.

You now have a clean, empty project and are ready to start building!

Chapter 2: A Guided Tour of the Unity Editor

The Unity Editor can look complex at first, but it's organized into several key windows, each with a specific purpose. Understanding this interface is the first major step in mastering Unity.

Understanding the Main Windows

Let's break down the default layout of the Unity Editor.

  • The Scene View (Center): This is your interactive, 3D workspace where you will build your game world. You can navigate this view to place, move, and manipulate all the objects in your game.

    • Navigation:

      • Orbit: Hold down the Alt key (Option on Mac) and the left mouse button, then drag to orbit around a central point.

      • Pan: Hold down the middle mouse button and drag to pan your view left, right, up, and down.

      • Zoom: Use your mouse scroll wheel to zoom in and out.



  • The Game View (Tab next to Scene View): This window shows you what the player will see through the game's camera. When you press the "Play" button at the top of the editor, the Game View becomes active, and you can test your game.

  • The Hierarchy (Left): The Hierarchy is a complete list of every object, or "GameObject," currently in your scene. A new scene starts with a "Main Camera" and a "Directional Light." If you add a cube, a character, or an enemy to your scene, it will appear in this list.

  • The Project Window (Bottom): This window acts as your project's file explorer. It contains all the assets that are part of your project but not necessarily in the current scene, such as 3D models, textures, materials, audio files, and scripts.

  • The Inspector (Right): The Inspector is a context-sensitive window. When you select a GameObject in the Hierarchy or an asset in the Project window, the Inspector displays all of its properties, settings, and components. This is where you will tweak values, attach scripts, and modify objects.

The Core Concepts: GameObjects and Components

To work effectively in Unity, you must understand two fundamental concepts: GameObjects and Components.

  • GameObject: Think of a GameObject as an empty container or a base object in your game. A character is a GameObject, a wall is a GameObject, and a light source is a GameObject. By themselves, they don't do much.

  • Component: Components are what give GameObjects their functionality and properties. They are the building blocks of your game. For example:

    • A Transform component (which every GameObject has by default) defines the GameObject's Position, Rotation, and Scale in the world.

    • A Mesh Renderer component renders a 3D model on the screen.

    • A Rigidbody component allows a GameObject to be affected by physics (like gravity).

    • A Collider component defines a physical shape for an object so it can collide with other objects.

    • A Script is also a component that you write to define custom behaviors.


This modular approach is incredibly powerful. You can create complex behaviors by adding and combining different components on a single GameObject.

Chapter 3: Creating the Game World

Now for the fun part: building the actual level for our game. We'll start with simple shapes and add color and light to bring it to life.

Building the Level Foundation

We will use Unity's built-in primitive shapes to construct a simple environment.

  1. Create the Ground:

    • In the Hierarchy window, click the "+" button (or right-click) and go to 3D Object > Plane.

    • This will create a flat plane in your scene. Select the "Plane" in the Hierarchy.

    • In the Inspector, look at the Transform component. Set its Position to (0, 0, 0) to center it in the world.

    • To make it larger, change its Scale to (5, 1, 5). This makes it 5 times wider and 5 times longer.


  2. Add Some Walls and Obstacles:

    • Create a few cubes to act as walls. In the Hierarchy, click + > 3D Object > Cube.

    • Select your new "Cube." In the Inspector, you can use the Transform component to change its Position, Rotation, and Scale.

    • You can also manipulate objects directly in the Scene View using the tools in the top-left:

      • Move Tool (W key): Lets you drag the object along the X, Y, and Z axes.

      • Rotate Tool (E key): Lets you rotate the object.

      • Scale Tool (R key): Lets you resize the object.


    • Duplicate objects by selecting them and pressing Ctrl + D (or Cmd + D on Mac). Create a few walls and platforms for your player to navigate.


Introducing Materials for Color and Texture

A grey world is boring. Let's add some color using Materials. A Material defines the visual properties of an object's surface, such as its color, shininess, and texture.

  1. Create a Materials Folder: In the Project window, right-click in the Assets area and go to Create > Folder. Name it "Materials". Keeping your project organized is a crucial habit.

  2. Create a New Material: Right-click inside your "Materials" folder and select Create > Material. Name it "GroundMaterial".

  3. Change the Color: Select the "GroundMaterial" asset. In the Inspector, you will see its properties. Find the "Albedo" property—this is its main color. Click the white color box next to it and choose a color, like a dark green or brown, for your ground.

  4. Apply the Material: To apply it, simply drag the "GroundMaterial" from the Project window and drop it onto the "Plane" GameObject in either the Scene View or the Hierarchy.

  5. Create a few more materials (e.g., "WallMaterial") with different colors and apply them to your other objects.

Setting Up Lighting

Lighting is essential for setting the mood of a 3D scene. By default, your scene has a "Directional Light" which acts like the sun, casting light from a single, infinitely far away direction.

  • Select the "Directional Light" in the Hierarchy.

  • In the Inspector, you can change its Rotation to alter the direction of the light and the length of the shadows.

  • You can also change its Color to give your scene a different tint (e.g., a slight yellow for a sunny day or a cool blue for a nighttime scene).

Finding Free Assets (Optional but Recommended)

While primitive shapes are great for prototyping, you'll eventually want more interesting models. The Unity Asset Store is an incredible resource integrated into the editor.

  • Go to Window > Asset Store and search for free 3D models.

  • For high-quality free assets, also check out external websites like Kenney.nl, Sketchfab (be sure to filter by "Downloadable"), and Poly Pizza. These are excellent resources for indie developers.

Chapter 4: Making the Player Move - C# Scripting Basics

A game isn't a game without interaction. It's time to bring our player to life with C# scripting, the primary programming language used in Unity.

Creating the Player GameObject

  1. First, let's create a simple representation for our player. In the Hierarchy, go to + > 3D Object > Capsule. A capsule is a common shape for character placeholders.

  2. Rename it to "Player". You can do this by right-clicking it in the Hierarchy and selecting "Rename".

  3. Position the player slightly above the ground plane so it doesn't start inside it. For example, set its Position to (0, 1, 0).

Introduction to C# Scripting

  1. Create a Scripts Folder: Just like with materials, let's stay organized. In the Project window, create a new folder named "Scripts".

  2. Create a C# Script: Right-click inside the "Scripts" folder and go to Create > C# Script. Name it "PlayerController". It is very important that the file name exactly matches the class name inside the script.

  3. Open the Script: Double-click the "PlayerController" script. This will open it in Visual Studio.

You will see a basic script template:

C#

using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class PlayerController : MonoBehaviour

{

    // Start is called before the first frame update

    void Start()

    {

        

    }


    // Update is called once per frame

    void Update()

    {

        

    }

}

  • Start(): This method is called exactly once when the script is first enabled, just before any of the Update() methods. It's perfect for initialization.

  • Update(): This method is called on every single frame. If your game runs at 60 frames per second, Update() is called 60 times per second. It's where most of the real-time game logic, like handling player input, goes.

Writing the Player Movement Script

Let's write code to move the player based on keyboard input. We will use a physics-based approach for smooth and realistic movement.

First, we need to add a Rigidbody component to our player. This will allow it to be controlled by Unity's physics engine.

  1. Select the "Player" GameObject in the Hierarchy.

  2. In the Inspector, click the "Add Component" button at the bottom.

  3. Search for "Rigidbody" and add it.

Now, modify your PlayerController script with the following code. Read the comments to understand what each part does.

C#

using UnityEngine;


public class PlayerController : MonoBehaviour

{

    // A public variable we can change in the Inspector to tweak the player's speed.

    public float moveSpeed = 5f;


    // A reference to our player's Rigidbody component.

    private Rigidbody rb;


    // A variable to store the player's movement input.

    private Vector3 movementInput;


    // Start is called before the first frame update

    void Start()

    {

        // Get the Rigidbody component attached to this GameObject and store it for later use.

        // This is an important optimization.

        rb = GetComponent<Rigidbody>();

    }


    // Update is called once per frame

    void Update()

    {

        // Get input from the horizontal (A/D keys or Left/Right arrows) and vertical (W/S keys or Up/Down arrows) axes.

        // The values range from -1 to 1.

        float horizontalInput = Input.GetAxis("Horizontal");

        float verticalInput = Input.GetAxis("Vertical");


        // Store the input in our Vector3 variable. We use the vertical input for the Z-axis for forward/backward movement.

        movementInput = new Vector3(horizontalInput, 0f, verticalInput);

    }


    // FixedUpdate is called at a fixed interval and is used for physics-based calculations.

    private void FixedUpdate()

    {

        // Move the Rigidbody. We normalize the input to prevent faster diagonal movement

        // and multiply by moveSpeed and Time.fixedDeltaTime to make the movement frame-rate independent.

        Vector3 moveVelocity = movementInput.normalized * moveSpeed;

        rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);

    }

}

Attaching the Script: Save your script in Visual Studio (Ctrl + S). Return to the Unity Editor. It will automatically compile the new code. Now, drag the "PlayerController" script from your "Scripts" folder and drop it onto the "Player" GameObject in the Inspector.

You can now see the script as a component on your player, and you'll see a "Move Speed" field that you can edit directly in the Inspector! Press the Play button at the top of the Editor. You should now be able to move your player capsule around the level using the W, A, S, D, or arrow keys.

Chapter 5: Cameras, Collisions, and Collectibles

Our player can move, but the camera is static. We also need to add objects for the player to interact with.

Setting Up a Follow Camera

We want the camera to follow the player. We'll do this with a simple script.

  1. Create a Camera Script: In your "Scripts" folder, create a new C# script called "CameraController".

  2. Write the Script: Open it and add the following code:

C#

using UnityEngine;


public class CameraController : MonoBehaviour

{

    // A public reference to the Player's Transform, which we will set in the Inspector.

    public Transform playerTransform;


    // The offset distance between the camera and the player.

    private Vector3 offset;


    // A public variable to control the smoothness of the camera follow.

    public float smoothSpeed = 0.125f;


    void Start()

    {

        // Calculate the initial offset between the camera's position and the player's position.

        offset = transform.position - playerTransform.position;

    }


    // LateUpdate is called after all Update functions have been called.

    // This is the best place to put camera logic, to ensure the player has already moved.

    void LateUpdate()

    {

        // Define the desired position for the camera.

        Vector3 desiredPosition = playerTransform.position + offset;

        // Smoothly interpolate from the camera's current position to the desired position.

        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);

        // Apply the new position to the camera.

        transform.position = smoothedPosition;

    }

}

  1. Attach the Script: Save the script and return to Unity. Select the "Main Camera" in the Hierarchy and attach the "CameraController" script to it.

  2. Assign the Player: You will see a "Player Transform" field in the script component which currently says "None (Transform)". You need to tell the camera which object to follow. Drag the "Player" GameObject from the Hierarchy into this slot.

Press Play. The camera should now smoothly follow your player as it moves around the level!

Understanding Colliders and Triggers

For our player to interact with walls and collectibles, we need to understand Colliders. A Collider is a component that defines a shape for an object for the purposes of physical collisions. Your player capsule and the cubes you created already have colliders by default (Capsule Collider and Box Collider, respectively). This is why your player doesn't fall through the floor or pass through walls.

A special type of collider is a Trigger. When a collider is set to be a "Trigger," it no longer acts as a physical barrier. Instead, it will simply detect when other colliders enter it and fire off an event in our code, which is perfect for collecting items.

Creating Collectible Items

  1. Create a Collectible: In the Hierarchy, create a 3D Object > Cube. Name it "Collectible". Make it smaller, perhaps with a Scale of (0.5, 0.5, 0.5).

  2. Make it a Trigger: Select the "Collectible". In the Inspector, find its "Box Collider" component and check the "Is Trigger" box.

  3. Add a Script for Rotation (Optional): To make it look more dynamic, create a simple script called "Rotator", add the following code, and attach it to the collectible.

C#

using UnityEngine;


public class Rotator : MonoBehaviour

{

    void Update()

    {

        // Rotate the object around the Y-axis at a rate of 15 degrees per second.

        transform.Rotate(new Vector3(0, 45, 0) * Time.deltaTime);

    }

}

  1. Create a Prefab: A Prefab is a reusable GameObject. Once you have your collectible set up, drag it from the Hierarchy into your Project window (perhaps into a new "Prefabs" folder). It will turn into a blue icon. Now you can drag multiple instances of this Prefab into your scene, and any change you make to the main Prefab will update all instances.

Detecting Collision and Collecting Items

Now, we need to modify our PlayerController script to detect when it touches a collectible.

  1. Tag the Collectible: Select your "Collectible" prefab in the Project window. In the Inspector, at the very top, click the "Tag" dropdown and select "Add Tag...". Click the "+" button, create a new tag named "Collectible", and save it. Now go back to the collectible prefab and assign it the "Collectible" tag you just created.

  2. Update the Player Script: Add the following method to your PlayerController.cs script, inside the class:

C#

// This function is called by Unity when this GameObject's collider enters another collider marked as a trigger.

    private void OnTriggerEnter(Collider other)

    {

        // We check if the object we collided with has the "Collectible" tag.

        if (other.gameObject.CompareTag("Collectible"))

        {

            // If it does, we deactivate the collectible object, making it disappear.

            other.gameObject.SetActive(false);

            

            // You could add code here to increase a score, play a sound, etc.

            Debug.Log("Collectible picked up!");

        }

    }

Press Play. Now, when your player touches one of the collectible cubes, the cube will disappear, and you will see the "Collectible picked up!" message in Unity's Console window (Window > General > Console).

Chapter 6: Creating a User Interface (UI)

A game needs a user interface to display information like score, health, or game-over messages. Let's create a simple score counter.

Introduction to Unity's UI System

  1. Create a Canvas: All UI elements must live inside a Canvas. In the Hierarchy, go to + > UI > Text - TextMeshPro. If this is your first time using TextMeshPro, Unity will prompt you to import essential resources. Click "Import TMP Essentials". This will automatically create a "Canvas" and an "EventSystem" in your Hierarchy, along with the Text object.

  2. The Canvas: The Canvas is the root object for all your UI. You can think of it as a separate overlay that is drawn on top of your game view.

  3. The Text Object: Rename your new Text object to "ScoreText". Select it. You will see it as a white box in your Scene View. You can switch to 2D view in the Scene View toolbar to make positioning UI easier. Position the "ScoreText" in one of the corners of the screen, like the top-left.

  4. Customize the Text: In the Inspector for "ScoreText", you can change the text content, font size, color, and alignment. Set the text to "Score: 0".

Updating the UI from Code

We need to make our script update this text every time we collect an item.

  1. Modify the PlayerController Script: We need to add a reference to the TextMeshPro component and a variable to keep track of the score.

C#

// Add this at the top of your script with the other 'using' statements.

using TMPro;


public class PlayerController : MonoBehaviour

{

    public float moveSpeed = 5f;


    // Add these new variables

    public TextMeshProUGUI scoreText; // A reference to the UI Text component.

    private int score = 0; // The player's current score.


    private Rigidbody rb;

    private Vector3 movementInput;

    

    // ... (Your Start, Update, FixedUpdate methods remain the same) ...


    private void OnTriggerEnter(Collider other)

    {

        if (other.gameObject.CompareTag("Collectible"))

        {

            other.gameObject.SetActive(false);


            // Increase the score

            score = score + 1;

            

            // Update the score text

            UpdateScoreText();

        }

    }


    // A new function to update the text display

    void UpdateScoreText()

    {

        scoreText.text = "Score: " + score.ToString();

    }

}

  1. Assign the UI Element: Save the script. Go back to the Unity Editor and select your "Player" GameObject. You will see a new empty field in your "Player Controller" component called "Score Text". Drag the "ScoreText" GameObject from your Hierarchy into this slot.

  2. Set Initial Text: We should also set the initial score text when the game starts. Add this line to your Start() method: UpdateScoreText();.

Now, press Play. The score will start at 0, and each time you collect an item, the text on the screen will update!

Chapter 7: Building and Sharing Your Game

You have a playable game loop! The final step is to build it into a standalone executable file that can be played on any PC without needing the Unity Editor.

Configuring Build Settings

  1. Open Build Settings: In the top menu bar, go to File > Build Settings.

  2. Add Open Scenes: The "Scenes In Build" list is empty. This tells Unity which scenes to include in the final game. Click the "Add Open Scenes" button to add your current, active scene.

  3. Choose Your Platform: In the "Platform" list on the left, ensure that "Windows, Mac, Linux" is selected. You can also choose the specific "Target Platform" (e.g., Windows).

  4. Player Settings (Optional): Click the "Player Settings..." button. Here you can set your "Company Name," "Product Name," and the game's icon.

Building the Executable

  1. Click "Build": In the Build Settings window, click the "Build" button. (Do not click "Build and Run" for the first time).

  2. Choose a Location: A file explorer window will open. It's best practice to create a new folder specifically for your build (e.g., create a folder named "Build" outside of your project's Assets folder). Select this folder.

  3. Let Unity Build: Unity will now compile your entire project, scripts, and assets into a finished game. This can take a few minutes.

Once it's finished, navigate to the folder you selected. You will see a .exe file with your product name and a "Data" folder. To play your game, simply run the .exe file! You can zip this entire folder and send it to your friends to play.

Conclusion and Next Steps

Congratulations! You have successfully designed, built, and exported your very first 3D game using Unity. You have learned the fundamentals of the Unity Editor, created a 3D level, written C# code for player movement and game logic, implemented a camera follow system, created collectibles, built a user interface, and compiled a standalone PC game.

This is just the beginning of your game development journey. The skills you've learned here are the foundation for creating much more complex and exciting games. Don't be afraid to experiment. Try changing the player's speed, building a more complex level, or designing new types of collectibles.

Here are some ideas for your next steps:

  • Create Enemies: Try adding a simple AI enemy that patrols an area.

  • Add a "Win" Condition: Make a special trigger that displays a "You Win!" message on the UI when the player reaches it.

  • Explore the Asset Store: Download some free 3D models and sound effects to make your game more polished.

  • Learn More About C#: Dive deeper into programming to create more complex game mechanics like health systems, inventories, or different weapon types.

Thank you for following along with this guide. We hope it has ignited a passion for game creation. If you have any questions or want to share what you've made, leave a comment below. Now go forth and build something amazing


Comments

Popular posts from this blog

Step-by-Step Guide on How to Create a GDD (Game Design Document)

How to Create a Brain Test–Style Puzzle Game in Unity (Step-by-Step Guide for Beginners)

Master Drag & Drop in Unity: Build Engaging Puzzle Games (Step-by-Step Tutorial)