Unity Basics Course: Network Lobby Screen – Create Room

Hello! Today, we will learn how to create a simple network lobby screen using Unity. In this tutorial, we will implement the room creation feature and explain how users can enter or create rooms. Let’s understand the basic concepts of network game development and practice using Unity’s networking features.

1. Unity and Networking

Unity is a powerful game engine that provides various features for network game development. The networking API provided by Unity, UNET (Unity Networking), helps to easily implement various networking functionalities. However, UNET is no longer actively supported, and it’s advisable to use Unity’s new networking solutions, Mirror or Photon. This tutorial will focus on creating a network room using Mirror.

2. Project Setup

Create a new project in Unity. Set the basic template of the project to 3D and name the project ‘NetworkLobby’. Then, let’s proceed with the following steps.

2.1 Installing the Mirror Package

1. In the top menu of the Unity Editor, select Window > Package Manager.

2. Click the + button and select Install from git URL….

3. Enter https://github.com/vis2k/Mirror.git in the URL input field.

4. Once the installation is complete, the Mirror package will appear in the package list.

2.2 Setting Up the Basic Scene

1. Select File > New Scene to create a new scene.

2. Create a Canvas to configure the basic UI. Right-click in the Hierarchy window and select UI > Canvas to add a new Canvas.

3. Add UI elements under the Canvas. Add buttons, input fields, and text to create the lobby screen.

3. Setting Up the Network Manager

The core of a network game is the Network Manager. The Network Manager manages the connection between clients and the server. In this process, we will set up the Network Manager and write basic code for room management.

3.1 Adding the NetworkManager

1. In the Hierarchy window, right-click and select Network > NetworkManager to add a new network manager.

2. Select the NetworkManager object and adjust the settings in the inspector. Remove the Fake Player Prefab in Spawn Info and add TelepathyTransport in the Transport section.

3.2 Writing a Custom Script

Write a controlling script to implement room creation and entry features. Create a new C# script and name it NetworkLobbyManager.cs.

using Mirror;
using UnityEngine;
using UnityEngine.UI;

public class NetworkLobbyManager : NetworkManager
{
    public InputField roomNameInput;
    public Button createRoomButton;
    public Button joinRoomButton;

    public override void OnStartServer()
    {
        Debug.Log("Server started!");
    }

    public void CreateRoom()
    {
        if (string.IsNullOrEmpty(roomNameInput.text))
        {
            Debug.Log("Room name cannot be empty!");
            return;
        }
        // Handle room creation
        Debug.Log("Room created: " + roomNameInput.text);
        NetworkServer.Listen(12345);
    }

    public void JoinRoom()
    {
        // Handle room entry
        Debug.Log("Joined room: " + roomNameInput.text);
        networkAddress = roomNameInput.text;
        StartClient();
    }

    public void OnEnable()
    {
        createRoomButton.onClick.AddListener(CreateRoom);
        joinRoomButton.onClick.AddListener(JoinRoom);
    }

    public void OnDisable()
    {
        createRoomButton.onClick.RemoveListener(CreateRoom);
        joinRoomButton.onClick.RemoveListener(JoinRoom);
    }
}

This script contains the basic logic for creating and entering rooms. It allows users to create or enter a room based on the room name they input.

4. UI Configuration

To improve user experience, adjust the UI layout and styles to configure the UI elements more specifically.

4.1 Configuring Inside the Canvas

1. Add a Panel under the Canvas. This panel will be the main background of the lobby.

2. Add a title text above the panel (e.g., “Game Lobby”).

3. Add room name input field along with buttons for creating and joining rooms.

4.2 Connecting Button Events

Connect the create and join room buttons to the methods of the network manager. In the Unity editor, assign the relevant methods to the buttons’ onClick() events.

5. Testing and Debugging

Once all functionalities are implemented, it is necessary to conduct final testing. Run several instances of the Unity editor to check if clients can create and enter rooms.

5.1 Running the Server

Click the Start Game button in the Unity editor to run the server. Ensure that the server is operating correctly.

5.2 Running the Client

With the server running, execute the client in another instance and enter the room. This process will allow you to see multiple clients interacting.

6. Conclusion

In this tutorial, we learned how to create a simple network lobby screen using Unity. We implemented basic features for room creation and entry using Mirror, and demonstrated how to enhance user experience through simple UI configuration and event handling.

Network game development becomes more fascinating the more you learn. Based on the basic knowledge gained in this tutorial, I encourage you to explore more complex network systems.

Thank you!

Unity basics course: Object collision

Unity is a powerful game engine that helps create a variety of games easily. In this tutorial, we will cover the basics of object collision handling in Unity. Collisions are an important element that create interactions between characters, enemies, and items in a game. Therefore, understanding collisions is the first step towards successful game development.

1. Understanding the Physics System in Unity

Unity manages interactions between objects through its built-in physics engine. The physics system is primarily implemented using the Rigidbody and Collider components.

1.1 Rigidbody

Rigidbody is a component that gives physical properties to an object. It allows the object to be affected by gravity or to be moved through applied forces. To use Rigidbody, follow these steps:

  1. Select the game object.
  2. Click the Add Component button in the Inspector window.
  3. Select Rigidbody from the Physics section.

1.2 Collider

A collider (Collider) is used to define the physical shape of an object. Colliders are not visually seen but enable collision detection. Unity has several types of colliders:

  • Box Collider: A rectangular prism-shaped collider.
  • Sphere Collider: A spherical collider.
  • Capsule Collider: A capsule-shaped collider.
  • Mesh Collider: A complex mesh-shaped collider.

2. Collisions and Triggers Between Objects

A collision occurs when two or more objects come into contact with each other. In Unity, there are two main ways to handle collisions:

  • Collision
  • Trigger

2.1 Collision

When objects collide, both objects will generate a physical response. To detect and respond to a collision, both objects must have a Rigidbody and Collider attached.

Handling Collisions

In Unity, methods such as OnCollisionEnter, OnCollisionStay, and OnCollisionExit can be used to handle object collisions. By defining these methods in a script, the logic for handling collisions can be implemented.

void OnCollisionEnter(Collision collision) {
    // Code executed when a collision starts
    Debug.Log("Collision occurred: " + collision.gameObject.name);
}

2.2 Trigger

A trigger is an object that does not generate a physical response even when a collision occurs. This means that even if objects overlap, there will be no response, only events will occur. To handle triggers, you must enable the Is Trigger option on the collider.

Handling Triggers

To handle triggers, methods like OnTriggerEnter, OnTriggerStay, and OnTriggerExit are used.

void OnTriggerEnter(Collider other) {
    // Code executed when a trigger occurs
    Debug.Log("Trigger occurred: " + other.gameObject.name);
}

3. Handling Collisions in a Real Project

Now, let’s create a simple sample project to understand how to handle collisions. In this project, we will implement a feature that makes the enemy object disappear when it collides with the player.

3.1 Project Setup

After creating a new 3D project in the Unity editor, add the following items:

  • Player Object: Add a cube-shaped object and attach Rigidbody and Box Collider.
  • Enemy Object: Add another cube-shaped object and attach Box Collider.

3.2 Writing the Script

Now, let’s write a script that makes the enemy object disappear when it collides with the player.

using UnityEngine;

public class Enemy : MonoBehaviour {
    void OnCollisionEnter(Collision collision) {
        if (collision.gameObject.CompareTag("Player")) {
            // Destroy the enemy object when colliding with the player
            Destroy(gameObject);
            Debug.Log("The enemy object has been destroyed by the player.");
        }
    }
}

3.3 Setting the Tag

Add a tag called Player to the player object. This allows the script to identify the player.

4. Optimization and Debugging

Physical events like collision handling can have a significant impact on performance. Therefore, optimization is necessary. Some optimization methods include:

  • Removing unnecessary colliders
  • Setting appropriate Rigidbody settings (Mass, Drag, etc.)
  • Using the FixedUpdate() method to process physics calculations

4.1 Debugging

Debugging can help resolve collision issues. If objects are not colliding, you should check the Is Trigger option and Rigidbody settings. Also, verify if the size and shape of the colliders are correct.

5. Conclusion

In this tutorial, we covered object collision handling in Unity in detail. We learned to understand the physics system and how to handle collision and trigger events. This foundational knowledge will serve as an important stepping stone toward creating more advanced games. You can enhance your skills through continuous practice and various projects.

In the next tutorial, we will discuss a more advanced topic, collision responses and physics-based animations. Thank you!

Unity Basics Course: What is a List?

Unity is a powerful engine widely used in game development, providing a user-friendly interface and various features to help developers efficiently create games. In this tutorial, we will explore one of the basic concepts of Unity, “List.” Lists are very useful tools for managing and manipulating data. We will start with the basic concepts, explore points to consider when using lists in Unity, and look at various use cases.

1. Basic Concept of Lists

A list is an ordered collection of elements with the same data type. This is a necessary concept that helps manage multiple variables efficiently. For example, in the case of a player’s inventory, it is convenient to store multiple items in a list. Lists can have dynamic sizes and possess the characteristic of adding or removing elements as needed.

1.1 Difference Between Lists and Arrays

Lists have several key differences from arrays. Arrays have a fixed size, and to change the size, you need to create a new array and copy the existing data. In contrast, lists are variable in size and can easily add or remove elements at runtime. This is a significant advantage in game development.

1.2 Declaring a List in C#

Unity uses C# for scripting. To use a list, you first need to include the System.Collections.Generic namespace. Then, you can declare a list as follows:

using System.Collections.Generic;

List<int> numbers = new List<int>();

The above code is an example of creating a list with integer elements. The element type of a list can be anything, and you can use not only basic data types but also user-defined classes.

2. Basic Methods of Lists

Lists provide various methods. In this section, we will look at some of the most commonly used methods.

2.1 Adding Elements to a List

To add elements to a list, use the Add() method:

numbers.Add(5); // Add 5 to the list

To add multiple elements at once, you can use the AddRange() method:

numbers.AddRange(new int[] { 1, 2, 3 }); // Add 1, 2, 3 to the list

2.2 Adding Elements at a Specific Index

To add an element at a specific index in a list, you can use the Insert() method:

numbers.Insert(0, 10); // Insert 10 at index 0

2.3 Removing Elements from a List

To remove elements from a list, you can use the Remove() or RemoveAt() methods:

numbers.Remove(5); // Remove 5 from the list
numbers.RemoveAt(0); // Remove element at index 0

2.4 Checking the Size of a List

To check the size of a list, you can use the Count property:

int size = numbers.Count; // Store the size of the list

3. Use Cases of Lists

Lists can be utilized in various ways in game development. Here are some use cases:

3.1 Inventory System

Using lists for implementing inventory in a game is very convenient. You can easily manage the list of currently available items by adding and removing items. Here’s a simple example of an inventory system:

using System.Collections.Generic;

public class Inventory
{
    private List<string> items = new List<string>();

    public void AddItem(string item)
    {
        items.Add(item);
    }

    public void RemoveItem(string item)
    {
        items.Remove(item);
    }

    public void ListItems()
    {
        foreach (var item in items)
        {
            Debug.Log("Item: " + item);
        }
    }
}

3.2 Managing Enemy NPCs

Managing enemy NPCs in a game using lists allows you to easily update each enemy’s state and remove them if necessary. For example:

using System.Collections.Generic;

public class EnemyManager : MonoBehaviour
{
    private List<Enemy> enemies = new List<Enemy>();

    public void AddEnemy(Enemy enemy)
    {
        enemies.Add(enemy);
    }

    public void UpdateEnemies()
    {
        foreach (var enemy in enemies)
        {
            enemy.Update();
            if (enemy.IsDead())
            {
                enemies.Remove(enemy);
            }
        }
    }
}

3.3 Custom Data Management

In Unity, you can save user-defined classes in lists to manage specific data. For example, you can manage player’s skills using a list:

using System.Collections.Generic;

public class Skill
{
    public string name;
    public int level;

    public Skill(string name, int level)
    {
        this.name = name;
        this.level = level;
    }
}

public class Player
{
    private List<Skill> skills = new List<Skill>();

    public void AddSkill(Skill skill)
    {
        skills.Add(skill);
    }
}

4. Advanced Techniques with Lists

Lists can be used effectively not only for simple data management but also through more advanced techniques. Here are some advanced techniques for utilizing lists.

4.1 Using LINQ for List Processing

In C#, you can use LINQ (Language Integrated Query) to easily work with lists. You can find elements matching specific conditions or sort data:

using System.Linq;

var sortedList = numbers.OrderBy(n >= n); // Sort the list
var filteredList = numbers.Where(n => n > 5).ToList(); // Filter elements greater than 5

4.2 Utilizing List Properties

Lists can be easily managed with various properties. For example, you can add properties for sorting lists, version control, and data filtering.

5. Considerations and Performance

There are several points to consider when using lists. Because lists have a dynamic size, adding or removing many elements can impact performance. To optimize performance, consider the following points:

5.1 Performance of List Initialization

Specifying the expected size when initializing a list can improve performance. You can create a list as follows:

List<int> numbers = new List<int>(100); // Initialize with size 100

5.2 Performance of Data Sorting and Searching

When sorting or searching for data in a list, you should choose the optimal method considering the complexity of the algorithms. If necessary, you can use binary search on sorted data to further improve performance.

5.3 Memory Optimization

Creating too many lists can increase memory usage. Avoid unnecessary lists and free up memory by using the Clear() method for lists that are no longer needed.

Conclusion

Lists are a powerful data structure in Unity that enables management of data in various forms. Compared to arrays, their flexibility and efficiency make them an essential tool in game development. Once you understand the basic concepts of lists, how to use their methods, and advanced techniques, you will be able to efficiently manage various data structures within your game. I hope this tutorial has helped you understand the importance and potential uses of lists.

I look forward to continuing this journey of exploring Unity’s various features and foundational concepts with you. For more information, feel free to explore various resources in the official documentation and community. Happy Coding!

Unity Basic Course: Resource Insertion

Many people starting game development choose Unity. Unity is an easy-to-use and powerful game engine, and it can be deployed to various platforms. In this tutorial, we will delve deeply into one of the basic concepts of Unity, which is resource insertion. This article will provide clear information on what resources are, the various types of resources, how to insert resources into Unity, optimization tips, and more so that you can firmly grasp the basics of Unity development.

1. What are resources?

In game development, resources refer to all assets used within the game. These can take various forms, such as graphics, sounds, textures, and animations. In Unity, these resources are called ‘assets’, and they are essential elements that make up a game.

For example, 3D models, audio files, and script files are all types of assets. These resources determine the visuals and interactive elements of the game, and they are crucial for creating a polished game.

2. Types of resources used in Unity

The types of resources used in Unity can generally be categorized as follows:

  • 3D Models: 3D objects that make up the visuals of the game. They typically use FBX or OBJ file formats.
  • 2D Sprites: Images used in 2D games. They are primarily used in PNG or JPG formats.
  • Textures: Images that adorn the surfaces of 3D models. Common formats include JPG, PNG, and TGA.
  • Audio Files: Sounds that occur in the game, capable of using WAV, MP3, and OGG file formats.
  • Animations: Files that define the movement of objects. Various animation effects can be implemented through Unity’s animation system.
  • Scripts: Code that handles the logic within the game, written in C#.

3. Inserting resources into a Unity project

Now, let’s learn how to insert resources into a Unity project. The process of inserting resources in Unity is simpler than you might think. Follow the steps below step by step.

3.1. Creating a Unity project

First, create a new project through Unity Hub. Unity Hub is a management tool for the Unity engine that allows you to manage multiple projects. When creating a new project, select a template (2D or 3D).

3.2. Accessing the Asset Store

Unity has an Asset Store that offers many free and paid resources. To access the Asset Store, select Window > Asset Store from the top menu.

3.3. Downloading resources

Search for the desired resource in the Asset Store and click the download button after selecting it. Once the download is complete, it will become available for use in your project.

3.4. Adding resources manually

In addition to downloading resources from the Asset Store, you can also add resources directly from local files. By dragging resources (images, models, etc.) into the Assets folder using the file explorer, they will be automatically added.

3.5. Verifying resources

After adding resources, you can verify them within the Unity editor. Open the Project window and check if the added assets appear. In this process, you can check the properties and components of the files, and if any additional settings are needed, you can adjust them in the inspector window.

4. Optimizing resources

After inserting resources, it’s important to optimize the game’s performance. Including many resources in the game can cause performance degradation, so you should consider the following optimization methods:

4.1. Texture compression

High-resolution textures can significantly impact performance. Reduce the size of textures and utilize Unity’s texture compression features to optimize them to the required resolution.

4.2. Reducing draw calls

Draw calls occur when the rendering engine sends data to the GPU. To minimize draw calls, you can merge as many meshes as possible into a single object or render objects that use the same texture together to enhance performance.

4.3. Reducing polygon count

Reducing the polygon count of 3D models can enhance performance. The polygon count determines the complexity of the model, so you should maintain intricate shapes only for models that players will see closely and create simpler forms for distant models.

4.4. Adjusting anti-aliasing (AA)

The anti-aliasing settings that smooth out the edges on the screen can affect the game’s performance. Adjust anti-aliasing appropriately according to the project’s needs and turn off the settings if they are unnecessary.

5. Conclusion

In this article, we explored in detail how to insert resources in Unity. Resources are fundamental elements in game development, and it’s essential to remember that proper usage and optimization significantly impact performance and quality. I hope this has helped you lay the groundwork necessary for developing fantastic games using Unity. May your journey in game development continue through more advanced features and case studies in future tutorials.

Thank you.

Unity Basics Course: Server and Lobby Access

Unity is a powerful tool for creating real-time multiplayer games. In this tutorial, we will cover in detail how to connect to a server and lobby in Unity. We will understand the basic networking concepts, set up communication between the server and client, and implement a lobby system.

Table of Contents

  1. Basics of Networking
  2. Setting Up Networking in Unity
  3. Building a Server
  4. Implementing a Client
  5. Creating a Lobby System
  6. Testing and Deployment

1. Basics of Networking

Networking refers to the process of sharing data between multiple devices. In multiplayer games, communication between the client (the user playing the game) and the server (the computer managing the game session) is essential. Here are the basic concepts of networking:

  • Client-Server Model: The client sends requests to the server, and the server provides responses to those requests.
  • Packet: The basic unit of data transmission. All data between the client and server is transmitted in the form of packets.
  • Latency: The delay time in data transmission. Low latency is crucial for gameplay.
  • Bandwidth: The speed of data transmission. Higher bandwidth allows for more data to be transmitted quickly.

2. Setting Up Networking in Unity

Unity provides its own networking library, and recently, Unity Netcode is widely used. This allows for easy and quick implementation of multiplayer features.

2.1 Installing Unity Netcode

To install Unity Netcode, follow these steps:

  1. Open the Unity editor and select your project.
  2. Open the package manager and search for “Unity Netcode”.
  3. Select the package and click the “Install” button to install it.

2.2 Basic Configuration

Once the installation is complete, you need to perform the basic settings. Proceed with the following configurations:

  • Select the “Player” option in the project settings.
  • Enable the necessary options in the network-related settings.

If you have completed the basic installation and configuration above, it is now time to implement the server and client.

3. Building a Server

The server manages the state information of all clients and handles the game’s logic. You can build a basic server using the following code:

C#
using Unity.Netcode;
using UnityEngine;

public class GameServer : MonoBehaviour
{
    void Start()
    {
        if (!NetworkManager.Singleton.IsServer)
        {
            NetworkManager.Singleton.StartHost();
        }
    }
}

The code above runs the host when the server starts. The client must be ready to connect to the server.

3.1 Role of the Server

  • Accept connection requests from clients
  • Manage game state
  • Send game data to clients

4. Implementing a Client

The client connects to the server and receives data from the server. Below is the basic code for implementing a client:

C#
using Unity.Netcode;
using UnityEngine;

public class GameClient : MonoBehaviour
{
    void Start()
    {
        NetworkManager.Singleton.StartClient();
    }
}

The client attempts to connect to the server at startup. Once the connection is established, it starts communicating game data.

4.1 Role of the Client

  • Request connection to the server
  • Receive data from the server
  • Send user input

5. Creating a Lobby System

The lobby system is a space where players gather before starting a game. The server must create a session, and clients should be able to connect to that session. The basic design of the lobby system is as follows:

  • The server manages the lobby information.
  • The client requests the lobby list and connects to the selected lobby.

5.1 Lobby Management Class

C#
using Unity.Netcode;
using UnityEngine;

public class LobbyManager : NetworkBehaviour
{
    public void CreateLobby()
    {
        // Lobby creation logic
    }

    public void JoinLobby()
    {
        // Lobby joining logic
    }
}

5.2 Client Interface

The client provides an interface for connecting to the lobby. Ensure that users can easily select a lobby through the UI.

6. Testing and Deployment

After implementing all systems, you need to test and deploy the game. In the testing environment, ensure that multiple clients can connect successfully, and that data is transmitted properly.

6.1 Testing Methods

  • Local Testing: Run multiple clients on the same computer to test.
  • Remote Testing: Run the server and clients on different computers to review network conditions.

6.2 Deployment

When deploying the game, choose a stable server environment, and make sure all necessary security settings are configured before deployment. You may also consider using cloud services.

Conclusion

In this tutorial, we learned how to set up a server and lobby system in Unity. We laid the groundwork for creating multiplayer games utilizing Unity’s powerful networking capabilities. Furthermore, consider various ways to construct complex game logic and improve user experience.

If you have any additional questions or need assistance, please leave a comment. Wishing you successful game development!