Basic Unity Course: Implementing Network Room Creation

In this course, we will learn how to implement the feature of creating a simple network room using the Unity engine. Unity is a widely used platform for game development, and the latest networking framework has made multiplayer game development easier than ever. This tutorial will cover the basics of using Unity and its networking features while explaining how to create and manage a simple multiplayer room.

1. Project Setup

Before starting with Unity, you need to set up a project. Follow the steps below:

  1. Run Unity Hub and create a new project.
  2. Select ‘3D’ as the template and appropriately name your project.
  3. Click the ‘Create’ button to create the project.

After creating the project, set up a basic scene through the Unity editor. Right-click in the Hierarchy window to add a new GameObject and select Terrain to create the basic terrain.

2. Installing the Networking Package

The basic networking functionality of Unity can be installed through the Unity Package Manager. Follow the steps below to install the package:

  1. Select Window > Package Manager.
  2. Click the plus (+) button and select ‘Add package from Git URL’.
  3. Enter the following URL to add the ‘Mirror’ package:
  4. https://github.com/vis2k/Mirror.git

Mirror is an open-source networking library for use with Unity. This package allows you to implement multiplayer games.

3. Setting up the Network Manager

To create a network room, you need to set up the NetworkManager. The NetworkManager is a crucial component that manages all network activities. Follow the steps below to set it up:

  1. Create an empty GameObject in the Hierarchy and rename it to ‘NetworkManager’.
  2. Add the ‘NetworkManager’ component to this GameObject.
  3. Also, add the ‘NetworkManagerHUD’ component to create a basic UI.

Now you are ready to set up the network room. NetworkManagerHUD provides a basic UI to create a host or connect a client.

4. Creating and Connecting to a Room

We will add functionalities to create and connect to a room within the game. You will need to write scripts for this. Follow the steps below:

4.1 Creating a Room Creation Script

  1. Create a Scripts folder in the Project window and create a ‘RoomManager.cs’ file inside it.
  2. Implement the room creation functionality by entering the following code:
  3. using UnityEngine;
    using Mirror;
    
    public class RoomManager : NetworkManager
    {
        public override void OnStartServer()
        {
            Debug.Log("Server starting");
        }
        
        public override void OnStartClient()
        {
            Debug.Log("Client connected");
        }
    
        public void CreateRoom()
        {
            NetworkServer.Listen(7777);
            Debug.Log("Room created");
        }
    
        public void JoinRoom()
        {
            NetworkClient.Connect("127.0.0.1", 7777);
            Debug.Log("Connecting to room...");
        }
    }

4.2 Connecting the UI and Script

  1. Connect the ‘CreateRoom’ method to be called when the ‘OnHostButton’ of NetworkManagerHUD is clicked.
  2. Set it up so that the ‘JoinRoom’ method is called when the ‘OnClientButton’ is clicked.

5. Setting up Player Prefab

When a player enters a room, you need to set what object will be instantiated. Here’s how to set up the player prefab:

  1. Create a new GameObject and name it ‘Player’.
  2. Add a ‘NetworkIdentity’ component to this GameObject and check ‘Local Player Authority’.
  3. Make this GameObject a Prefab and save it in the Resources folder.
  4. Add the following code to the RoomManager script to set the player prefab:
  5. public GameObject playerPrefab;
    
        public override GameObject OnStartPlayer(NetworkConnection conn)
        {
            return Instantiate(playerPrefab);
        }

6. Testing and Debugging

Now that all the settings are complete, it’s time to run a test. Check if the network room creation and client connection work properly:

  1. Click the ‘Play’ button in the Unity editor to start the server.
  2. Run a new instance of Unity editor to connect the client.
  3. Check the console logs of both server and client to verify the connection status.

7. Conclusion

You have now implemented the basic functionalities of creating and connecting to a simple network room. Through this, you have gained an understanding of the fundamentals of multiplayer game development, and learned the necessary steps to add more complex networking features in the future.

Based on what you learned from this course, you can expand on it by implementing features such as:

  • Implementing a room listing feature
  • Adding voice or text chat functionality
  • Implementing custom player character spawning features

Network development in Unity has endless possibilities. Continue to explore the joy of multiplayer game development through various practice and experiments.

Unity Basics Course: Shooting 1 – Shooting with Bullets

Hello! In this course, we will create a simple shooting game using Unity. The main focus of our implementation will be on the “shooting bullets” feature. We will gradually learn the necessary functions and aim to complete a simple game at the end.

Table of Contents

  1. Installing Unity and Basic Setup
  2. Creating a Project
  3. Setting Up a 2D Game Environment
  4. Creating a Bullet Prefab
  5. Writing the Character and Bullet Shooting Script
  6. Configuring and Testing Game Objects
  7. Conclusion

1. Installing Unity and Basic Setup

To install Unity, first download Unity Hub from the Unity website. After installing Unity Hub, install the desired version of the Unity Editor. Once the installation is complete, you can run Unity Hub to create a new project.

2. Creating a Project

In Unity Hub, click the New Project button and select the 2D template. Name the project ShootingGame and set the save location, then click the Create button to create the project.

3. Setting Up a 2D Game Environment

Once the project is created, the Unity Editor will open. Here, we will place game objects and set up the camera and background.

3.1 Setting Up the Camera

Select the main camera and adjust the viewport to an appropriate size. In a 2D game, it’s common to set the camera’s Projection to Orthographic.

3.2 Adding a Background

Add an image to be used as the background in the Assets folder. Then drag it to the scene to place it. Set the z-axis value of the image lower than that of the camera to ensure the background is visible.

4. Creating a Bullet Prefab

We will create a simple sprite representing the bullet. Add the bullet sprite to the Assets folder and place it into the scene as a 2D object. After adjusting the size and properties of the bullet, drag this object into the Prefabs folder to save it as a prefab.

4.1 Setting Bullet Properties

Select the prefab and add a Rigidbody2D component. This component gives physical properties so that the bullet can move naturally. Set the Gravity Scale to 0 so that it is not affected by gravity.

4.2 Adding a Collider

Add a CircleCollider2D to the bullet prefab to set up the collider. This collider allows the bullet to detect collisions with other objects.

5. Writing the Character and Bullet Shooting Script

Now we need to write a script to control the shooting of the bullet. Let’s create the character and add the shooting functionality.

5.1 Creating the Character

Prepare a sprite to be used as the character and add it to the scene in the editor. Also, add a Rigidbody2D component to the character.

5.2 Writing the Script

Create the script for the character. Below is a basic C# script example to shoot bullets.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public GameObject bulletPrefab; // Bullet prefab
    public float bulletSpeed = 20f; // Bullet speed

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) // When the space bar is pressed
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
        Rigidbody2D rb = bullet.GetComponent();
        rb.velocity = transform.up * bulletSpeed; // Set the bullet's speed in its direction
    }
}

5.3 Connecting the Script

Add the written script to the character object and set the bulletPrefab variable to the bullet prefab in the inspector window.

6. Configuring and Testing Game Objects

All components are prepared, so let’s test if the game works well.

6.1 Running the Test

Click the play button to run the game. Check if the bullet is fired when the character presses the space bar. If needed, you can adjust the speed or direction to achieve the desired outcome.

6.2 Testing Bullet Collisions

It’s also important to add handling for when the bullet collides with other objects. For example, you could make the enemy disappear when hit by a bullet. To do this, write a script for the enemy object to check for collisions with the bullet.


using UnityEngine;

public class Enemy : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Bullet"))
        {
            Destroy(gameObject); // Destroy the enemy object
        }
    }
}

Conclusion

In this course, we implemented a simple shooting mechanism using Unity. By learning the basic functions of shooting bullets and handling collisions, we have laid the groundwork for game development and a stepping stone for more advanced programming. I hope you continue to create various games with Unity!

This concludes the Unity Basics Course – Shooting 1: A Shooting Tutorial Using Bullets. If you have any questions or comments, please leave them below. Thank you!

Introduction to Unity: Function Calls

Unity is a globally renowned game engine that helps game developers bring their ideas to life. In this tutorial, we will take an in-depth look at one of the fundamentals of Unity: ‘Function Calls’. A function is a block of code that performs a specific task and plays a crucial role in game development.

1. What is a function?

In programming languages, a function is a collection of code that performs a specific task and can return a value as needed. The main advantages of functions are code reusability, readability, and ease of maintenance. By breaking complex tasks into units called functions, developers can modify and test each part independently.

2. Defining functions in Unity.

In Unity, games are developed using C#. Functions in C# are defined in the following format:

returnType functionName(parameters)
{
    // Function code
}

Here’s a simple example. This function adds two integers and returns the result:

int AddNumbers(int a, int b)
{
    return a + b;
}

3. Calling Functions

Once a function is defined, it can be called at any time. A function call is made in the following format:

returnType result = functionName(arguments);

Now, let’s call the previously defined AddNumbers function:

int result = AddNumbers(5, 10); // result will be 15.

4. Unity’s Update() Function

In Unity, there is a special function called Update() that is called every frame. This function contains code for continuously updating the state of game objects.

void Update()
{
    // Code called every frame
    if (Input.GetKey(KeyCode.Space)) 
    {
        Debug.Log("The space bar has been pressed.");
    }
}

5. Functions with Parameters

Functions can receive external data through parameters. Multiple data can be passed to functions, making them more useful. We will also look at how to use default parameters, optional parameters, and variable-length parameters.

5.1 Default Parameters

int Multiply(int a, int b = 2) 
{
    return a * b;
}

The function above has two parameters, but b has a default value of 2. Therefore, calling Multiply(5) will result in 10.

5.2 Variable-length Parameters

Using variable-length parameters allows you to adjust the number of arguments passed to the function dynamically:

int Sum(params int[] numbers) 
{
    int total = 0;
    foreach(int number in numbers) 
    {
        total += number;
    }
    return total;
}

When calling this function, you can pass any number of integers:

int total = Sum(1, 2, 3, 4); // total is 10.

6. Functions with Return Values

Functions can return values externally. This return value can be used in the function call site. The type of the return value must be specified when defining the function, and a function defined as void does not return a value.

string GetMessage() 
{
    return "Hello, and welcome to the world of Unity!";
}

7. Exception Handling and Functions

It is also important to handle exceptions that may occur during function calls. In C#, you can handle exceptions using try-catch blocks:

void ExampleFunction()
{
    try
    {
        int result = 10 / 0; // Error occurs.
    }
    catch (DivideByZeroException ex)
    {
        Debug.Log("Cannot divide by zero: " + ex.Message);
    }
}

8. Recursive Function Calls

A recursive function is a function that calls itself. This is a powerful way to solve specific problems by breaking them down into simpler subproblems. For example, we can write a recursive function to calculate the Fibonacci sequence:

int Fibonacci(int n) 
{
    if (n <= 1) return n;
    return Fibonacci(n - 1) + Fibonacci(n - 2);
}

9. Example of Game Development Using Functions

Now, let's apply functions to actual game development in Unity. We will look at a simple example of implementing a character's jumping ability:

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Jump();
    }
}

void Jump()
{
    GetComponent().AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}

10. Conclusion

In this tutorial, we explored various ways to define and call functions in Unity. Functions are fundamental building blocks of all programming languages and are essential for performing various tasks in game development. Through practice and hands-on experience, enhance your understanding of function calls and create your own games!

Unity Basic Course: Pathfinding Artificial Intelligence

In game development, pathfinding AI plays a role in allowing each game object that can move to understand the environment and efficiently find a path towards a given goal. In this course, you will learn the fundamental principles and implementation methods of pathfinding AI using the Unity engine. Through this course, we will explore how to build practical pathfinding AI using basic AI concepts and Unity’s NavMesh system.

1. What is Pathfinding AI?

Pathfinding AI is a form of artificial intelligence that autonomously allows an object to move to its destination by calculating the optimal path (either many-to-many or single) based on the starting position and goal position in a given environment (map). It is commonly used in games and robotics, playing a crucial role in solving complex pathfinding problems.

1.1. The Necessity of Pathfinding

In a game environment, pathfinding AI is essential when NPCs (Non-Player Characters) or player’s assisting characters need to navigate around obstacles to reach a designated goal. For example, pathfinding algorithms are used when enemies track the player or allies move to specific points.

2. Introduction to Unity’s NavMesh System

NavMesh, a powerful tool for implementing pathfinding AI in Unity, helps calculate various paths and allows characters to move appropriately. NavMesh is a pre-calculated network of paths that enables game objects to move freely.

2.1. Features of NavMesh

  • Pathfinding based on a navigation mesh
  • Handling obstacles in the surrounding environment
  • Real-time dynamic obstacle handling
  • Accessible via a simple API

2.2. Setting Up NavMesh in Unity

  1. After creating a project, build the necessary environment.
  2. Add the ‘NavMesh Obstacle’ component to the objects where NavMesh will be applied.
  3. Open the ‘Navigation’ panel in the Unity editor, and select the Bake menu to redraw.
  4. Add the ‘NavMesh Agent’ component to the character that will be used as an ‘Agent’.

3. Implementing Pathfinding AI

Now, we will write the following script in Unity to implement pathfinding AI that can be used in actual games.

3.1. Setting Up NavMesh Agent

NavMesh Agent is AI that allows a character to move toward the target point along the NavMesh. Here is a basic example of a NavMesh Agent script:

using UnityEngine;
using UnityEngine.AI;

public class AIFollow : MonoBehaviour
{
    public Transform target; // Target point
    private NavMeshAgent agent;

    void Start()
    {
        agent = GetComponent(); // Get the NavMeshAgent component
    }

    void Update()
    {
        if(target != null)
        {
            agent.SetDestination(target.position); // Move to the target point
        }
    }
}

3.2. Setting the Target Point

The target point can be set by the user clicking in the game or specifying a particular object. The method for setting the target point via user input is as follows:

void Update()
{
    if (Input.GetMouseButtonDown(0)) // On left mouse button click
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            target.position = hit.point; // Set the target point to the clicked position
        }
    }
}

4. Applying Obstacle and Evasion Techniques

To make the pathfinding AI more realistic and natural, obstacle evasion techniques are necessary. Unity’s NavMesh can recognize dynamically generated obstacles and help the character avoid them effectively.

4.1. NavMesh Obstacle

Dynamic obstacles are objects that can change position while moving. To accommodate this, the NavMesh Obstacle component should be applied, and the ‘Carve’ option can be activated to allow NavMesh to recognize and navigate around the obstacle.

4.2. Evasion Algorithm

By adding a simple evasion algorithm, the character should be able to recognize and avoid surrounding obstacles while moving toward the user-defined target point. Additional logic can be written as follows:

void AvoidObstacles()
{
    RaycastHit hit;
    if (Physics.Raycast(transform.position, agent.velocity.normalized, out hit, 1f))
    {
        if (hit.collider != null && hit.collider.CompareTag("Obstacle"))
        {
            // Add evasion behavior when an obstacle is detected
            Vector3 avoidDirection = Vector3.Reflect(agent.velocity, hit.normal);
            agent.velocity = avoidDirection * agent.speed; // Adjust speed in the direction to avoid
        }
    }
}

5. Practical Example

Now, let’s create a simple practical example to complete the pathfinding AI based on what we’ve learned so far.

5.1. Requirements

Create a project with the following features:

  • Characters respond to user input and move to the target point
  • Artificial intelligence that avoids obstacles
  • Basic understanding of the game environment and three-dimensional space

5.2. Project Setup

Run Unity, create a new project, and set up a basic environment that includes trigger objects and colliders. Here, we will specifically set up the NavMesh to be used.

6. Conclusion

This course taught you the basic methods for implementing pathfinding AI in Unity. With the NavMesh system, you were able to implement obstacle avoidance and efficient pathfinding. Furthermore, you have gained a foundation to use this technology to implement AI for various game objects. Now, advance the AI design further to suit different types of games and apply complex algorithms.

7. Additional Materials and References

If you would like to delve deeper into the topics covered in this course, please refer to the materials below:

Unity Basic Course: Managing Enemy Character Health

Unity is one of the most widely used engines in game development. It provides the flexibility and powerful features to create games on various platforms, but there are many elements to understand and handle. In this article, I will explain in detail how to implement and manage the health of enemy characters using Unity. This process assumes a basic knowledge of C# programming. Through this tutorial, strengthen the foundation of game development and enhance the fun and challenge of your game.

1. Understanding the Concept of Enemy Characters and Health

In games, the health points (HP) of enemy characters are a very important element. Health determines how much damage the player needs to inflict to defeat the enemy character. When the health reaches zero, the enemy character dies, which can trigger various reactions in the game. By managing health, you can adjust the difficulty of the game and enhance the user experience.

2. Project Setup

First, create a new Unity project and set up a 2D or 3D game environment. The setup process is as follows:

  1. Run Unity.
  2. Click the ‘New Project’ button.
  3. Specify the project name and path, and select a template (2D or 3D).
  4. Click the ‘Create’ button to create the project.

3. Creating an Enemy Character Script

Now let’s write a script to manage the health of the enemy character. Create a new C# script and name it `Enemy`. This script will include the enemy character’s health, damage values, and health reduction methods. The following code shows a basic enemy character health management script.


using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float maxHealth = 100f; // Maximum health
    private float currentHealth; // Current health

    void Start()
    {
        currentHealth = maxHealth; // Set initial health
    }

    // Method called when taking damage
    public void TakeDamage(float damage)
    {
        currentHealth -= damage; // Reduce health
        Debug.Log($"Enemy took {damage} damage. Current health: {currentHealth}");

        if (currentHealth <= 0)
        {
            Die(); // Handle death
        }
    }

    private void Die()
    {
        Debug.Log("Enemy died."); // Death message
        Destroy(gameObject); // Delete game object
    }
}

4. Implementing the Enemy Character Health System

Before implementing the health system, let's create an enemy character object that can interact with Unity's physics engine. Create or use a new 3D model for the enemy character and adjust its position. Follow the steps below.

  1. Right-click in the Hierarchy window and select ‘3D Object’ > ‘Cube’ to add the enemy character.
  2. Change the name of the Cube to ‘Enemy’.
  3. Drag the previously created `Enemy` script onto the Enemy game object to add it.

5. Handling Enemy Damage

Now we need to implement a system that can inflict damage on the enemy. We will add a method that is called when the player attacks the enemy. To do this, we will need to call the function that inflicts damage on the enemy character from the player management script.


using UnityEngine;

public class Player : MonoBehaviour
{
    public float damage = 20f; // Attack power
    public GameObject enemy; // Reference to the enemy character object

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)) // Attack with spacebar
        {
            AttackEnemy();
        }
    }

    private void AttackEnemy()
    {
        if (enemy != null)
        {
            enemy.GetComponent().TakeDamage(damage); // Deal damage to the enemy
        }
    }
}

6. Displaying Enemy Character Health in UI

To visually display the enemy's health in the game, we can add a UI element. Unity allows for easy implementation of health bars using its UI system. Proceed with the steps below.

  1. Right-click in the Hierarchy window and select ‘UI’ > ‘Canvas’ to add a canvas.
  2. Right-click within the Canvas and select ‘UI’ > ‘Slider’. This slider will act as the health bar.
  3. Change the `Name` of the slider to ‘HealthBar’ and set the slider value to start from 1.

Then, add a method to update the health bar in the `Enemy` script.


using UnityEngine;
using UnityEngine.UI;

public class Enemy : MonoBehaviour
{
    public float maxHealth = 100f; 
    private float currentHealth; 
    public Slider healthBar; // Health bar slider

    void Start()
    {
        currentHealth = maxHealth; 
        if (healthBar != null)
        {
            healthBar.maxValue = maxHealth;
            healthBar.value = currentHealth;
        }
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage; 
        Debug.Log($"Enemy took {damage} damage. Current health: {currentHealth}");

        if (healthBar != null)
        {
            healthBar.value = currentHealth; // Update health bar
        }

        if (currentHealth <= 0)
        {
            Die(); 
        }
    }

    private void Die()
    {
        Debug.Log("Enemy died."); 
        Destroy(gameObject); 
    }
}

7. Testing the Enemy Character Health System

All settings are complete. Now let’s test the game to see if the enemy character health system works correctly.

  1. Click the Play button at the top of Unity to run the game.
  2. The Cube set as the enemy character should be visible on the game screen.
  3. Press the Space key to inflict damage on the enemy and check that the health bar updates.
  4. Check that when the enemy’s health reaches zero, the enemy dies and disappears.

8. Implementing Additional Features

Although the basic health system implementation is complete, you can enhance it with additional features to create a more polished health system. For example:

  • Add different types of enemy characters: Introduce enemy characters with various maximum health and damage values to increase the game's diversity.
  • Health recovery system: Create enemy characters that recover health over time.
  • Death animation: Add an animation when the enemy character dies to enhance immersion.
  • Sound effects: Add sound effects when the enemy takes damage or dies to improve the game's quality.

9. Conclusion

In this tutorial, we learned how to manage the health of enemy characters in Unity. The health system is simple but essential to the game, and by implementing it properly, you can enhance the fun and challenge of the game. Expand the system with additional features and create your unique game. Game development using Unity offers limitless possibilities, and your creativity will be your most valuable asset.

Don’t be afraid to take your first steps into the world of game development. As you accumulate small successes and gain experience, you will be able to successfully lead larger projects in the future. I hope you continue to practice and deepen your learning based on what you learned in this tutorial today.