Unity Basics Course: Reusable Objects – Prefabs

Hello! I have prepared this basic course for everyone who wants to learn Unity. Unity is a powerful engine widely used for game development, equipped with various features that enable efficient development. Among them, the Prefab feature allows developers to easily manage reusable objects, significantly enhancing development productivity. In this article, we will explore the basic concepts of prefabs and various ways to utilize them in detail.

What is a Prefab?

A prefab is a feature in Unity that allows you to store and reuse a blueprint of a game object. Simply put, it is a system that lets you create a single object and replicate it for use in multiple places. By using prefabs, you can create the same object multiple times, and if you modify one prefab, the changes will be reflected in all objects that use that prefab. This helps maintain consistency in the game and offers convenience in development and maintenance.

The Process of Creating a Prefab

  1. Creating an Object

    Create a new game object in the Unity editor. You can drag a 3D model or sprite into the scene. For example, try adding a simple cube or sprite.

  2. Setup and Configuration

    Add the necessary components to the game object and set the desired values. For instance, you can add a Rigidbody to apply physics effects, or add a script to give it special behaviors.

  3. Converting to Prefab

    Once your game object is set up, click on it and drag it into the prefab folder in the browser window after clicking the ‘Create’ button in the toolbar. This saves the game object as a prefab.

Benefits of Using Prefabs

By using prefabs, developers can enjoy various benefits, such as:

  • Reusability: Once created, a prefab can be easily reused in multiple scenes and games. There is no need to configure each instance of the same object separately.
  • Consistency: All prefab objects use the same settings, minimizing inconsistencies within the game. For example, if you modify the enemy character prefab, all enemy characters in the game will be updated uniformly.
  • Efficiency: Prefabs allow for efficient management of game objects and help keep code concise. This is especially useful in large-scale game development when collaborating with team members.

Examples of Prefab Usage

Prefabs can be utilized in various ways. Here are some key examples:

1. Enemy Character Prefab

You can easily manage enemy characters used in the game through prefabs. Add scripts and set various properties for the enemy character prefab. By doing this, if you want to change the behaviors or appearances of the enemy characters, you can do so by modifying the prefab, which will apply the changes across the game.

2. Item Prefab

Create item prefabs for items (weapons, armor, potions, etc.) that can be found in the game. After setting up scripts and properties, place these item prefabs within the game. This ensures consistent functionalities when the player picks up or uses specific items.

3. UI Element Prefab

Utilize prefabs for buttons, panels, and other UI elements that compose the game’s user interface (UI) for efficient UI assembly. By creating various UI elements as prefabs, you can dynamically generate them in your scripts.

Managing Prefabs

It is important to manage prefabs correctly. When there are many prefabs, maintaining an appropriate folder structure and setting naming conventions is essential. As the project grows, finding and managing prefabs can become challenging, so consider the following tips:

  • Group by creating separate folders for characters, items, UI, etc.
  • Use clear and consistent naming conventions. For example, use a structure like ‘Enemy_Orc’, ‘Item_HealthPotion’.
  • Set less frequently changed prefabs to ‘Read-only’ to prevent accidental modifications.

Optimizing Prefabs

Optimizing prefabs with performance in mind is also very important. When using multiple prefab objects, rendering performance can be affected. You can optimize using the following strategies:

1. Instance Optimization

When multiple prefabs need to be used, it is advisable to reuse a single instance multiple times. For example, when placing complex terrains or objects, it is beneficial to use the same prefab to create instances. This improves rendering performance.

2. Using LOD (Level Of Detail)

Set up LOD for prefabs to use low-resolution models for distant objects and high-resolution models for close objects. This improves performance.

3. Removing Unnecessary Components

Inspect each prefab to ensure that no unnecessary components have been added, and remove any redundant elements. In particular, prefabs with physical effects or unnecessary scripts can negatively impact performance.

Conclusion

Prefabs are a very important concept in Unity that enables efficient object reuse and management. We have explored various examples and utilization methods, so I encourage you to apply them to your projects. By actively using prefabs in your future Unity development, you will enhance productivity and develop a consistent game. I hope this course has been helpful in your Unity development journey. Thank you!

Basic Unity Course: C# Float

Unity is a popular game engine widely used for 2D/3D game development. C# is the primary programming language for writing scripts in Unity, enabling powerful and efficient programming. In this blog, we will delve deep into the float data type in C#.

1. Introduction to C# Data Types

C# has several basic data types, one of which is float. The float type is used to store floating-point numbers, and this data type can contain decimal values. Float is one of the widely used basic data types, particularly when dealing with graphics or physical computations.

2. Characteristics of float

Range: A float can have values from -3.402823E38 to 3.402823E38.
Precision: Float provides 7 digits of decimal precision.
Memory Usage: It uses 32 bits (4 bytes) of memory.

3. Difference between float and double

In C#, besides float, there is a data type called double for representing floating-point numbers. Double uses 64 bits (8 bytes) and provides approximately 15-16 digits of decimal precision. Therefore, float uses relatively less memory but has lower precision, while double uses more memory but offers higher precision. The choice between these two data types depends on the user’s needs.

4. Declaring and initializing float variables in C#

To declare a float variable in C#, you use the ‘float’ keyword followed by a variable name, and you can initialize it if necessary. Here is a basic code example that declares and initializes a float variable:


float myFloat = 5.75f; // The 'f' suffix indicates that this value is explicitly a float.

5. Operations on float values

Various mathematical operations can be performed on float values. Here are examples of basic addition, subtraction, multiplication, and division:


float a = 10.5f;
float b = 2.5f;
float sum = a + b; // Addition
float difference = a - b; // Subtraction
float product = a * b; // Multiplication
float quotient = a / b; // Division

These operations are performed according to the precedence of the operators. For instance, multiplication and division are handled before addition and subtraction.

6. Precision and errors of float

Since float represents floating-point numbers, small errors may occur in the calculation results. This is a common phenomenon arising from the binary representation method used internally by computers. To minimize such errors, especially in tasks requiring high precision like financial and scientific calculations, it is advisable to use double.

7. Example of float usage – Game Development

In game development, float is mainly used to represent physical properties such as position, velocity, and rotation. For example, when a character moves, you can specify its position using float variables:


public class Player : MonoBehaviour
{
    public float speed = 5.0f;

    void Update()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        transform.position += movement * speed * Time.deltaTime;
    }
}

This code implements a simple logic that moves the player object left, right, and back and forth. The Update method is called every frame, where it takes input and handles movement.

8. Converting float to string

To convert a float value to a string, you can use the ToString() method. For example:


float score = 95.75f;
string scoreString = score.ToString("F2"); // Convert to a string with 2 decimal places

The above code converts the score value to a string with two decimal places.

9. Arrays and lists of float

You can also store float values in an array or a list. For example, you can declare a float array like this:


float[] scores = new float[5] { 85.5f, 90.0f, 75.0f, 88.5f, 92.0f };

When using a list, you need to use the System.Collections.Generic namespace:


using System.Collections.Generic;

List scoreList = new List { 85.5f, 90.0f, 75.0f };

10. Example application: Game score calculation

You can use float variables to calculate scores in a game. Below is a simple example of score calculation:


public class ScoreManager : MonoBehaviour
{
    private float score;

    void Start()
    {
        score = 0.0f; // Initial score
    }

    public void AddScore(float points)
    {
        score += points; // Add score
    }

    public float GetScore()
    {
        return score; // Return current score
    }
}

11. Conclusion

The float data type in C# is useful in game development and programming in general. It allows you to handle physical properties and computations, and it can be applied in various situations. However, one must also understand the limitations of float’s precision and the possibility of errors occurring.

Through this tutorial, I hope you gained an understanding of the basics and applications of the float data type in C#, and I encourage you to apply this knowledge in actual game development. I hope to further your understanding through various basic Unity tutorials in the future.

In the next tutorial, we will discuss other data types in C# and their usage, as well as more complex data handling methods. Until then, I hope you maintain your passion for programming and game development.

Unity Basics Course: Installing Unity

If you are interested in game development, it is essential to understand the game engine called Unity. Unity offers an intuitive interface and powerful features, making it widely used from beginners to experts. In this article, I will explain in detail the basic installation process of Unity.

What is Unity?

Unity is a cross-platform game engine that was first released in 2005. With Unity, you have all the tools needed to create 2D and 3D games. One major advantage is the ability to distribute games on various platforms, including Windows, macOS, Linux, iOS, and Android.

Preparing for Unity Installation

System Requirements

Before installing Unity, you need to check whether your computer meets the system requirements. Below are the basic system requirements:

  • Operating System: Windows 7 SP1, Windows 10, macOS 10.12 (Sierra) or newer
  • Processor: Multi-core processor, SSE2 support
  • RAM: At least 4GB of RAM
  • Graphics Card: Graphics card that supports DX10 (Shader Model 3.0)
  • Disk Space: Minimum of 10GB of free space

Downloading Unity

To install Unity, you need to download it from the official Unity website. Below are the steps to download:

  1. Visit the official Unity website (https://unity.com/).
  2. Click on ‘Get Started’ or ‘Download’ in the top menu.
  3. Select the version to use: Unity offers a free Personal version and a Pro version for businesses. If you are a personal developer, it is recommended to choose the Personal version.
  4. Account Creation: You may need to create a Unity account to download. Enter your email address and password to create an account.
  5. Click the download button to download the installer.

Unity Installation Process

The process of installing Unity by running the downloaded installer is as follows:

  1. Double-click the downloaded installer to run it.
  2. When the installation wizard opens, click ‘Next’ or ‘Yes’ to proceed.
  3. Agree to the license agreement. Carefully read the contract and click the ‘Agree’ button if you agree.
  4. Select the components to install. Choose the necessary items like the Unity Editor, example projects, and documentation. The Unity Editor is required by default.

Installing the Unity Editor

The Unity Editor is the primary tool used for game development. Once the installation is complete, you can run the editor to create projects.

  1. After Unity installation is complete, launch the Unity Editor from the desktop or start menu.
  2. When the Unity Editor is launched for the first time, you need to log in with your account. Enter the Unity account you created earlier and log in.
  3. After logging in, click the ‘New’ button to create a new project.
  4. Select the project name and location, and choose one of the 2D or 3D templates.
  5. Finally, click the ‘Create’ button to create the project.

Project Setup and Creating the First Scene

Now that the Unity project is set up, let’s create a simple scene.

  1. After creating the project, start by understanding the various panels in the Unity Editor (Hierarchy, Scene, Inspector, etc.).
  2. In the Hierarchy panel, click the ‘Create’ button to add a game object. For example, select ‘3D Object’ and then ‘Cube’ to add a cube.
  3. Adjust the position, size, and rotation of the cube in the Scene view to place it where you want it.
  4. In the Inspector panel, you can make detailed settings, such as adding Material to the cube or changing its color.

Adding a Simple Game Script

The power of Unity lies in the ability to implement game logic through code scripts. Let’s add simple behavior to the cube using a C# script.

  1. Select the cube in the Hierarchy panel, then click the ‘Add Component’ button at the bottom of the Inspector panel.
  2. Select ‘New Script’ and name it ‘CubeController’, then create a script using C#.
  3. A script file will be automatically generated, and double-clicking it will open the default code editor.
  4. Paste the code below and save it:
  5.         using UnityEngine;
    
            public class CubeController : MonoBehaviour
            {
                void Update()
                {
                    if (Input.GetKey(KeyCode.UpArrow))
                    {
                        transform.Translate(Vector3.forward * Time.deltaTime);
                    }
                    if (Input.GetKey(KeyCode.DownArrow))
                    {
                        transform.Translate(-Vector3.forward * Time.deltaTime);
                    }
                }
            }
        
  6. Now switch to play mode to see if the cube moves up and down.

Troubleshooting and Tips

Let’s look at common problems and solutions that may occur during the Unity installation and setup process.

Problem: Editor Won’t Open

If the editor won’t open or an error occurs, try the following methods:

  • Restart your computer and try again.
  • Update to the latest graphics drivers.
  • Check if your antivirus program is blocking the Unity Editor from executing.

Problem: Login Error

If you encounter an error when logging in with your Unity account:

  • Make sure you entered your username and password correctly.
  • Create a new password and try again.

Conclusion

The Unity installation process is very simple, and learning the basic installation methods opens up the possibility to develop various games. In this article, we covered the basic installation process of Unity and how to set up your first project. Now that you understand the basics of Unity, you can learn more advanced topics through various tutorials.

I’m cheering for you as you take your first steps into the world of game development! I hope you create amazing games through Unity in the future.

Basic Unity Course: Bullet Creation

1. Introduction

In this course, we will cover how to create a simple bullet using the Unity game engine. Bullets are a very important element in game development, and we will address how bullets work, their firing mechanisms, and collision handling. Through this course, you will gain an understanding of the fundamental concepts of Unity and get hands-on experience with C# scripting.

2. Required Tools and Environment Setup

2.1. Installing Unity

To install Unity, visit the official Unity website and download the latest version of Unity Hub. After launching Unity Hub, you can download and install the desired version of Unity.

2.2. Creating a New Project

In Unity Hub, click the “New” button to create a new 3D project. Set the project’s name to “BulletShooter” and create it.

3. Creating a Basic Bullet Object

3.1. Adding a 3D Object

In the project window, right-click and select 3D Object > Sphere. The created sphere object will represent the bullet. With the object selected, adjust the Scale value in the inspector window to (0.2, 0.2, 0.2) to set its size.

3.2. Creating a Bullet Material

In the project window, right-click and select Materials > New Material. Name the new material “BulletMaterial”, select a color, and drag and drop it onto the sphere to apply the material.

3.3. Adding a Rigidbody Component to the Bullet Object

To allow the bullet to move physically, click Add Component in the property window and search for Rigidbody to add it. This component enables gravity and physical interactions.

4. Writing the Bullet Firing Script

4.1. Creating the Script

In the project window, create a Scripts folder and then create a script named Bullet.cs inside it. This script will define the behavior of the bullet.

4.2. Writing the Script Code

Open the Bullet.cs file and enter the following code:


using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float speed = 20f;
    public float lifetime = 2f;

    void Start()
    {
        Rigidbody rb = GetComponent();
        rb.velocity = transform.forward * speed;

        Destroy(gameObject, lifetime);
    }
}
    

The code above sets the speed and lifetime of the bullet when it is fired. The Start method is called when the script is activated, setting the bullet’s speed through the Rigidbody component, and the bullet is destroyed after a certain amount of time.

5. Creating the Player and Bullet Firing System

5.1. Creating the Player Object

To add a player that can fire bullets, select 3D Object > Cube to create the player object. Adjust the player’s size and position to create an appropriate shape.

5.2. Writing the Player Script

To add the ability for the player to fire bullets, write a script named PlayerController.cs. The content of this script is as follows:


using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public GameObject bulletPrefab;
    public Transform bulletSpawnPoint;

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Fire();
        }
    }

    void Fire()
    {
        Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
    }
}
    

The above script calls the Fire method to instantiate a bullet when the player presses the “Fire1” input (typically the left mouse button).

6. Setting Up the Spawn Point

To set the position where bullets are fired from, create an empty game object as a child of the player object. Name this empty game object “BulletSpawnPoint”. Adjust the position of this object to match the player’s muzzle.

6.1. Connecting the Script

Select the player object and drag the PlayerController script into the inspector to add it. Then, link the bullet prefab to the Bullet Prefab field and drag the newly created empty game object to link it to the Bullet Spawn Point.

7. Final Check and Testing

7.1. Creating the Bullet Prefab

To create a bullet prefab, drag the bullet object from the project window and drop it into the Prefabs folder. You can now delete the original object.

7.2. Running the Game

Run the game to test if the player can fire bullets. By clicking the left mouse button, you should see the bullets being instantiated and fired.

8. Implementing Additional Features

8.1. Implementing Collision Handling

To handle when the bullet collides with other objects, simply add the OnTriggerEnter method to the Bullet.cs script:


void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Enemy"))
    {
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
}
    

This code removes the enemy and destroys the bullet when the bullet collides with an enemy.

8.2. Fine-tuning and Additional Elements

To make the game more complete, you can add bullet trajectories, firing animations, sound effects, and more. Explore various Unity features related to these aspects as you expand the project.

9. Conclusion

In this tutorial, we learned how to implement a basic bullet using Unity. It was an important process for laying the foundation in game development, and I hope you will expand your game by adding more complex features in the future. Experimenting and learning more will help you create various game elements.

Unity Basics Course: Creating an Ending Screen – Victory

Introduction

Hello! In this course, we will learn how to create an ending screen in Unity for games. We will particularly focus on the ending screen that will be displayed when a victory condition is met. The ending screen plays a significant role in game development as it provides important feedback to the player and greatly influences the overall gaming experience. In this article, we will explain the components of the ending screen, UI design, script writing methods, and more in detail.

1. Understanding the Ending Screen

The ending screen is the screen displayed to the player at the last stage of the game. It appears when the victory conditions are satisfied, and typically consists of the following elements:

  • Victory message
  • Score, rank, and other statistical information
  • Restart button
  • Button to return to the main menu
  • Background image or animation

2. Setting Up the Unity Project

First, open the Unity project and create a new scene for the ending screen. Follow these steps:

  1. In the Unity Editor, click the File menu and select New Scene.
  2. Name the scene EndingScreen and save it.
  3. Right-click in the Hierarchy panel and choose UI -> Canvas to create a canvas.
  4. Add various UI elements under the canvas.

3. Configuring the UI

Now, let’s set up the necessary UI elements for the ending screen. The basic elements needed for the ending screen include:

3.1. Adding a Victory Message

Add text under the Canvas to display the victory message. To add text:

  1. Right-click on the Canvas in the Hierarchy and select UI -> Text.
  2. Modify the properties of the Text object to write the victory message. For example, you can use the message “Congratulations! You have won!”.

3.2. Displaying Scores and Statistics

To show the score and statistics obtained in the game, add another Text element.

  1. Right-click on the Canvas in the Hierarchy and select UI -> Text.
  2. Modify the properties of the Text object to dynamically update the score information by connecting a script.

3.3. Adding Buttons

Add buttons that allow the player to restart or return to the main menu. Here’s how to add buttons:

  1. Right-click on the Canvas in the Hierarchy and select UI -> Button.
  2. Replace the button text with phrases like “Restart” or “Main Menu”.
  3. Adjust the button size and position in the Inspector window to make it look good.

4. Adding Scripts

Now that the UI elements of the ending screen are ready, let’s write a script to display this screen when the victory condition occurs. You can use the following approach:

4.1. Creating the EndingScreenManager Script

Follow these steps in the Unity Editor to create the script:

  1. Create a Scripts folder in the Project view.
  2. Right-click in the Scripts folder, select Create -> C# Script, and name it EndingScreenManager.
  3. Double-click the script to open it in the code editor.

4.2. Writing the Script Code

Here is a basic code example for the EndingScreenManager script:


using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class EndingScreenManager : MonoBehaviour
{
    public GameObject endingScreen;
    public Text scoreText;

    void Start()
    {
        endingScreen.SetActive(false);
    }

    public void ShowEndingScreen(int score)
    {
        endingScreen.SetActive(true);
        scoreText.text = "Your Score: " + score.ToString();
    }

    public void RestartGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    public void GoToMainMenu()
    {
        SceneManager.LoadScene("MainMenu");  // Change MainMenu to the actual scene name.
    }
}
    

4.3. Connecting UI Elements and the Script

Now that the script is ready, let’s connect the UI elements to the script:

  1. Select the Canvas in the Hierarchy panel, then add the EndingScreenManager script.
  2. Drag and connect the GameObject of the ending screen to the Ending Screen field of the EndingScreenManager component.
  3. Drag and connect the Text object that will display the score to the Score Text field.

5. Displaying the Ending Screen at Game End

Set up the game to call the ShowEndingScreen method to display the ending screen when the game ends. You can add the following code at the location where the victory condition is confirmed:


if (playerHasWon)
{
    endingScreenManager.ShowEndingScreen(playerScore);
}
    

6. Decorating the Ending Screen

The ending screen should also be visually appealing. Here are some tips for creating an attractive ending screen:

  • Use color combinations that match the background image.
  • Add animation effects to create excitement about the ending.
  • Adjust the font style of the text to enhance readability.

Conclusion

This tutorial guided you on how to create an ending screen in Unity. By showing the ending screen at the right moment when the victory condition is satisfied and providing a congratulatory message and statistical information to the player, you can offer a more satisfying gaming experience. Now, add a fantastic ending screen to your game to give players an unforgettable moment!

Appendix

If you have any additional information or questions, please leave a comment. If you want more Unity-related tutorials, please subscribe to the blog!