h1: Unity Basics Course: What is a Class?

In software development, a class is a fundamental component of object-oriented programming (OOP). When using game engines like Unity, classes play a crucial role in understanding the structure and flow of game development. In this article, we will explore the definition and principles of classes, their application in Unity, and provide real examples to gain a deeper understanding of the concept of classes.

1. What is a Class?

A class is a framework for modeling objects from the real world. In object-oriented programming, an object is a unit that contains data (attributes) and behavior (methods), and a class serves as a blueprint for creating such objects. A class defines the form of data and the methods that manipulate that data, and you can create instances of the class to use in practice.

1.1 Components of a Class

  • Attributes (Fields): Data defined in the class. For example, in a car class, attributes can include color, model, manufacturer, etc.
  • Methods: Actions that the class can perform. In the car class, functionalities like “drive” and “stop” can be defined as methods.
  • Constructor: A special method that is called when creating an instance of the class. It is used to set initial attributes.

2. Using Classes in Unity

Unity uses the C# language for scripting. All scripts are defined in the form of classes, and many features in Unity use classes. For example, Unity components like Sprite, Rigidbody, and Camera are all classes.

2.1 Creating a Class

To create a class in Unity, you need to create a new C# script and add the class definition inside it. Below is an example of writing a simple class:

using UnityEngine;

public class Car : MonoBehaviour
{
    public string color;
    public int speed;

    void Start()
    {
        color = "Red";
        speed = 20;
    }

    void Update()
    {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    }
}

2.2 Inheritance of Classes

Classes can create new classes based on other classes through inheritance. Inheritance is useful for increasing code reusability and clarifying the relationships between classes. For example, you can create a base class called ‘Vehicle’ and generate two subclasses called ‘Car’ and ‘Bike’.

using UnityEngine;

public class Vehicle
{
    public float speed;

    public void Move()
    {
        Debug.Log("Moving at speed: " + speed);
    }
}

public class Car : Vehicle
{
    public void Honk()
    {
        Debug.Log("Car is honking!");
    }
}

public class Bike : Vehicle
{
    public void RingBell()
    {
        Debug.Log("Bike bell rings!");
    }
}

3. Classes and Objects

After defining a class, you need to create objects based on that class in order to use it. An object is an instance of a class, and you can create multiple objects based on the same class.

Car myCar = new Car();
myCar.color = "Blue";
myCar.speed = 30;

4. Advantages of Classes

  • Code Reusability: You can easily add new functionalities by inheriting or reusing existing classes.
  • Encapsulation: You can manage data and methods as a single unit, which makes code maintenance easier.
  • Polymorphism: You can define different behaviors with the same method name in different classes.

5. Class Example: Simple Game Object

The example below creates a simple ‘Player’ class and implements a simple mechanism for player interaction in the game. This example must inherit from Unity’s MonoBehaviour.

using UnityEngine;

public class Player : MonoBehaviour
{
    public float health = 100f; // Player's health

    // Method to take damage from an enemy
    public void TakeDamage(float amount)
    {
        health -= amount;
        Debug.Log("Player hit! Health: " + health);
        
        if (health <= 0)
        {
            Die();
        }
    }

    // Actions when the player dies
    private void Die()
    {
        Debug.Log("Player died!");
        // Add death handling logic
    }
}

6. Practice Utilizing Classes

Now, let’s practice utilizing classes by creating a simple game object.

  1. Create a Unity Project: Create a new Unity project.
  2. Create Player.cs File: Write the 'Player' script and paste the code above.
  3. Create GameManager.cs File: Create a 'GameManager' class to manage the flow of the game and write logic for spawning the player and handling damage.
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public Player playerInstance;

    void Start()
    {
        // Create and initialize player instance
        playerInstance = new Player();
        playerInstance.health = 100;
        
        // Deal damage to the player
        playerInstance.TakeDamage(20);
    }
}

Conclusion

Classes are a core concept in many programming languages, including Unity. The use of classes improves code readability, eases maintenance, and enables efficient development. Through this tutorial, you should understand the concept of classes and how to utilize them in Unity, laying the foundation for implementing more complex game logic.

In future tutorials, we will cover more advanced concepts such as polymorphism, interfaces, and abstract classes. Along with this, we will have the opportunity to apply practical game development examples to experience the utilization of classes and objects in Unity.

© 2023 Unity Basics Course. All rights reserved.

Unity Basics Course: Player Synchronization and Attack Synchronization (RPC Communication)

Recently, the trend in game development has emphasized the importance of networking and synchronization due to the rising popularity of multiplayer games. In this course, we will take a closer look at player synchronization and attack synchronization in Unity. We will explore how to implement interactions between player characters over the network using RPC (Remote Procedure Call) communication.

1. What is Unity?

Unity is an integrated development environment (IDE) for game development. This platform supports the development of both 2D and 3D games and provides powerful tools for deployment across various platforms. The Unity engine uses the C# programming language to write scripts and offers an intuitive user interface.

2. The Need for Multiplayer Games

In modern games, a multiplayer experience where players can interact with each other is essential. Player synchronization helps multiple users to reflect each other’s actions in real-time within the same game world. This results in a more dynamic and immersive gameplay experience.

2.1 The Importance of Synchronization

Synchronization is a key element in overcoming issues such as network latency and packet loss, ensuring that all players share the same game state. Improperly implemented synchronization can lead to inconsistencies between players and diminish the game’s reliability.

3. Networking in Unity

Unity offers various networking solutions. Multiplayer functionalities can be easily implemented through libraries such as Unity’s UNet, Mirror, and Photon. In this course, we will use Photon Networking.

3.1 Installing Photon Networking

To install Photon Networking, download and install the “Photon PUN 2 – Free” package from the Unity Asset Store. After installation, sign up for the Photon Server and create an App ID to apply to your project.

4. Implementing Player Synchronization

The basic principle of player synchronization is to propagate player actions occurring on each client to all clients. To achieve this, we synchronize the player’s position, rotation, and state using Photon’s networking features.

4.1 Writing the Player Script


using Photon.Pun;
using UnityEngine;

public class PlayerController : MonoBehaviourPunCallbacks, IPunObservable
{
    private float moveSpeed = 5f;
    private Vector3 networkPosition;

    void Update()
    {
        if (photonView.IsMine)
        {
            Move();
        }
        else
        {
            LerpPosition();
        }
    }

    void Move()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(horizontal, 0, vertical) * moveSpeed * Time.deltaTime;
        transform.position += movement;
    }

    void LerpPosition()
    {
        transform.position = Vector3.Lerp(transform.position, networkPosition, Time.deltaTime * 5);
    }

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
        {
            stream.SendNext(transform.position);
        }
        else
        {
            networkPosition = (Vector3)stream.ReceiveNext();
        }
    }
}

4.2 Code Explanation

Here, we use the Photon.Pun library to synchronize the player’s position. We implement the IPunObservable interface and override the OnPhotonSerializeView method. This method defines the data to be sent over the network. When the client controls its own object, it updates the position, while the positions of other clients are smoothly reflected through Lerp interpolation.

5. Implementing Attack Synchronization

Attack synchronization between player characters is an important interaction in games. When an attack is performed, that action needs to be propagated to all players to facilitate interactions among them. This can be implemented through RPC communication.

5.1 Writing the Attack Script


using Photon.Pun;
using UnityEngine;

public class AttackController : MonoBehaviourPunCallbacks
{
    public void Attack()
    {
        if (photonView.IsMine)
        {
            photonView.RPC("PerformAttack", RpcTarget.All);
        }
    }

    [PunRPC]
    void PerformAttack()
    {
        // Implement the actual attack logic
        Debug.Log("Attack performed!");
        // For example, logic to damage an enemy
    }
}

5.2 Code Explanation

In the updated script, we use photonView.RPC to notify all other clients to perform the attack when the Attack() method is called. The RpcTarget.All parameter ensures that the attack method is executed on all clients. The PerformAttack() method is called on all clients and executes the actual game logic.

6. Testing and Debugging

Once all scripts are ready, perform tests to ensure that synchronization occurs correctly during player attacks and movements. Click the ‘Play’ button multiple times in the Unity editor to run several instances and review interactions between different clients.

6.1 Troubleshooting Detected Issues

To resolve networking or synchronization issues, check the following points:

  • Check frame rates and network bandwidth to improve performance.
  • Apply appropriate compression techniques during data transmission to reduce the amount of data sent.
  • Adjust the frequency of packet transmission to minimize network packet loss.

Conclusion

In this course, we explored the process of implementing player synchronization and attack synchronization through RPC communication in Unity. Synchronization is a very important factor in multiplayer games and can greatly enhance user experience. We learned how to easily implement powerful multiplayer features using Unity and Photon. Based on this knowledge, I encourage you to implement more complex features and develop various games in the future.

Additional Resources

For more information and advanced feature learning, please utilize the following resources:

If you found this course helpful, subscribe to the blog to receive more useful information!

Unity Basic Course: Restrictions on Entering Playing Rooms

In this tutorial, we will explain the ‘Room Entry Restriction’ feature, which is one of the essential functions when developing multiplayer games in Unity. Through this tutorial, you will learn how to manage access to the game’s rooms. This feature plays a significant role in enhancing the quality of player experience across various genres, including blockchain games, MMORPGs, and FPS.

1. Before You Start

You need to understand the basic concepts of Unity and networking, as well as have a fundamental understanding of creating multiplayer games. In this tutorial, we will implement the room entry feature using Mirror Networking.

2. Setting Up Mirror Networking

2.1. Installing Mirror

Mirror is an advanced networking library for Unity. Follow the steps below to install Mirror.

  • Open Unity’s Package Manager.
  • Add https://github.com/vis2k/Mirror.git in the Git URL.
  • Install Mirror.

2.2. Basic Setup

After installing Mirror, you need to set up the following:

  • Create a NetworkManager game object.
  • Add the NetworkManager component.
  • Add the NetworkManagerHUD component for easy UI setup.

3. Implementing Room Entry Restriction Logic

3.1. Writing Room Creation Code

using Mirror;
using UnityEngine;

public class RoomManager : NetworkBehaviour
{
    private int maxPlayers = 4; // Maximum number of players

    public void CreateRoom()
    {
        if (NetworkServer.active) return;

        var room = new GameObject("Room");
        NetworkServer.Spawn(room);
    }
}

3.2. Implementing Room Entry Logic

You can check the maximum number of players in the room with the following code:

public class RoomManager : NetworkBehaviour
{
    private List connections = new List();

    public override void OnServerAddPlayer(NetworkConnection conn)
    {
        if (connections.Count >= maxPlayers)
        {
            conn.Disconnect(); // Disconnect if the number of players exceeds the maximum
            return;
        }
        
        base.OnServerAddPlayer(conn);
        connections.Add(conn); // Add new player
    }
}

4. Adding UI and Feedback

4.1. Displaying the Number of Players

You can display the current number of players in the room through the UI. Create a Canvas and add a Text UI to show the number of connections in real-time.

4.2. Providing Feedback When Entry is Restricted

if (connections.Count >= maxPlayers)
{
    Debug.Log("The room is full, and no more players can enter.");
    // Provide additional UI feedback
}

5. Testing and Debugging

Now that the code and UI are ready, let’s test the multiplayer functionality in the Unity editor. Run each client and enter the room to debug and fix any errors more thoroughly.

6. Conclusion

In this tutorial, we learned how to implement the room entry restriction feature in Unity. These fundamental models in multiplayer games can greatly enhance the quality of player experience. We encourage you to challenge yourselves with better game development through various features and optimization work.

7. Additional Resources and References

Unity Basics Course: Collision Information Detection

Collision detection is one of the several important elements in game development. It helps manage interactions between objects and is essential for implementing the game’s logic. In this course, we will explore the basic concepts of collision detection in Unity and how to implement it.

1. What is Collision Detection?

Collision detection is the process of determining whether two objects in a game are touching each other. This process is handled automatically through the game’s physics engine, and Unity implements it using Collider and Rigidbody components. Collision detection is necessary for various game mechanics. For example, it occurs when a player attacks an enemy, collects an item, or collides with an obstacle.

2. Unity’s Physics System

Unity features a powerful physics system based on the NVIDIA PhysX physics engine. This system uses two main components for collision detection:

  • Collider: The shape used for collision detection. It defines the space occupied by an object in 3D space.
  • Rigidbody: A component that applies physical properties, providing effects like gravity, collision, and friction.

2.1 Collider Component

Colliders are divided into 2D and 3D shapes, and the types include:

  • Box Collider: A rectangular cuboid collider.
  • Sphere Collider: A spherical collider.
  • Capsule Collider: A capsule-shaped collider.
  • Mesh Collider: A collider used for complex-shaped objects. Note that mesh colliders are calculated asynchronously, which can impact performance.

2.2 Rigidbody Component

The Rigidbody enables physical interactions, defining collisions and responses. Objects with a Rigidbody attached move under the influence of the physics engine and respond to external forces.

The main properties of the Rigidbody component include:

  • Mass: Defines the mass of the object.
  • Drag: A value that sets air resistance.
  • Angular Drag: Sets resistance based on angular velocity.
  • Use Gravity: Determines whether the object is affected by gravity.
  • Is Kinematic: Sets the Rigidbody to ignore physical interactions.

3. Implementing Collision Detection

Now that we understand the basic concepts, let’s look at how to implement collision detection in Unity.

3.1 Project Setup

First, launch Unity and create a new 3D project. Then, create basic 3D objects (e.g., Cubes, Spheres) and add the necessary components to each object.

3.2 Adding Collider and Rigidbody to Objects

Add the appropriate Collider to each object:

  • Add a Box Collider to the Cube.
  • Add a Sphere Collider to the Sphere.

Now, add a Rigidbody to each object. This will allow the physics engine to manage each object.

3.3 Adding Scripts

Now, let’s add a script for collision detection. Write the following code in a new C# script and attach it to the object.

using UnityEngine;

public class CollisionHandler : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision)
    {
        Debug.Log("Collision detected: " + collision.gameObject.name);
    }
}

The above code will log information to the console every time a collision occurs. Now, run the play mode, and when the two objects collide, you will see the collision message in the console.

3.4 Various Collision Detection Methods

Unity provides several methods related to collision detection. The following are commonly used methods:

  • OnCollisionEnter: Called when a collision starts.
  • OnCollisionStay: Called every frame while colliding.
  • OnCollisionExit: Called when a collision ends.

Additionally, you can use Trigger (when the Is Trigger option of the collider is enabled) to achieve even more diverse collision detection.

3.5 Trigger Collision Detection

Let’s learn how to detect the points where colliders overlap using a Trigger. A Trigger allows specific events to occur without physical response when objects collide.

using UnityEngine;

public class TriggerHandler : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        Debug.Log("Trigger detected: " + other.gameObject.name);
    }
}

Applying this script to an object will enable Trigger collision detection. After setting up the Trigger, you can verify the output in the console when the Trigger occurs.

4. Utilizing Collision Detection

You can use collision detection to add various functionalities to your game. Here are a few use cases:

4.1 Scoring System

You can set up the game to gain points when the player collides with items. This allows you to implement the game’s goals and reward system.

4.2 Game Over Conditions

You can build a system to trigger a game over when the player collides with enemies. This enhances the thrill of gameplay.

4.3 Level Progression

You can add events that change levels when the player collides with specific objects. This allows players to satisfy storylines and challenges.

5. Considering Optimization

The performance of collision detection can affect the overall performance of the game. Here are some ways to optimize collision detection:

  • Use simple colliders: Use basic graphic shape colliders instead of complex mesh colliders.
  • Deactivate objects: Disable the Rigidbody of objects that do not require collision in certain situations to improve processing performance.
  • Raycasting: Use raycasting as needed to detect physical interactions along a virtual line.

Conclusion

In this course, we learned about collision detection in Unity. We covered how to use the basic Collider and Rigidbody components, as well as how to implement collision detection. These concepts are crucial in game development and are essential in forming various game mechanics. Aim to understand the basics of collision detection and utilize them to create unique game logic. In the next lesson, we will learn how to implement more complex game mechanics through collision detection.

Unity Basics Course: Trying Out Unity

Unity is a powerful platform widely used for game development and real-time 3D content creation. In this course, you will learn the basic concepts of Unity, how to install the program, and how to create a simple project. Unity offers various tools and features to make it easy for users of all levels to access and learn.

1. What is Unity?

Unity is a cross-platform game engine that was first released in 2005 and has gained great popularity ever since. Unity supports both 2D and 3D game development and can be deployed across various platforms (PC, mobile, console, etc.). Its main features include powerful graphics rendering, a physics engine, and a user-friendly editor.

1.1 Features of Unity

  • Cross-platform support: Can be deployed to various platforms with a single development effort.
  • User-friendly interface: Intuitive UI and drag-and-drop functionality.
  • Strong community: Supported by extensive resources, tutorials, and forums.
  • Scalability and flexibility: Functionalities can be extended through various plugins and assets.
  • Free and paid versions: Offers a free version suitable for individuals or small projects.

2. Installing Unity

To use Unity, you first need to install it. Here are the steps to install:

2.1 Installing Unity Hub

Unity Hub is a tool used to manage the Unity Editor and projects. Follow these steps to install:

  1. Visit the official Unity website to download Unity Hub.
  2. Run the downloaded file to complete the installation.

2.2 Installing Unity Editor

Install the Unity Editor through Unity Hub:

  1. Run Unity Hub and go to the “Install” tab.
  2. Click the “Install New” button.
  3. Select the desired version of Unity and click “Next”.
  4. Select any necessary additional modules (e.g., Android Build Support) and complete the installation.

3. Creating Your First Project

Once the installation is complete, let’s create your first project:

3.1 Creating a New Project

  1. Navigate to the “Projects” tab in Unity Hub.
  2. Click the “New” button.
  3. Set the project name and save path, select a template, and then click the “Create” button.

3.2 Introduction to the Editor Interface

When you create a project, the Unity Editor opens. The editor interface consists of the following main elements:

  • Scene View: Shows the 3D space that composes the current scene.
  • Game View: Provides a preview of what the final game will look like when executed.
  • Hierarchy Panel: Lists all objects present in the current scene.
  • Inspector Panel: Allows you to adjust the properties of selected objects.
  • Project Panel: Manages all assets in the project.

4. Placing Objects

Now, let’s place your first object in the scene.

4.1 Adding a Basic Object

  1. Right-click in the Scene View and select “3D Object” > “Cube”.
  2. The cube is added to the scene and also appears in the Hierarchy Panel.
  3. You can adjust the cube’s position, rotation, and scale in the Inspector Panel.

5. Adding Scripts

In Unity, you can add functionality to objects by writing scripts in C#. Let’s write a simple script.

5.1 Creating a Script

  1. Right-click in the Project Panel and select “Create” > “C# Script”.
  2. Name the script and double-click to open it in Visual Studio or your IDE.

5.2 Writing a Basic Script

public class CubeRotation : MonoBehaviour
{
    void Update()
    {
        transform.Rotate(new Vector3(0, 1, 0) * Time.deltaTime * 50);
    }
}

The above code sets the cube to rotate around the y-axis every frame.

5.3 Applying the Script

  1. Drag the created script onto the cube object in the scene to apply it.
  2. Press the play button in the Game View to confirm that the cube is rotating.

6. Creating a Simple Game

Now, let’s create a simple game. The goal is for the cube’s color to change when the player clicks on it.

6.1 Writing a Color Change Script

using UnityEngine;

public class CubeColorChange : MonoBehaviour
{
    void OnMouseDown()
    {
        GetComponent().material.color = Random.ColorHSV();
    }
}

The script above sets the cube to change to a random color each time it is clicked.

6.2 Applying the Script

  1. Write the above script in a new C# script file and drag it onto the cube to apply it.
  2. Click the play button in the Game View again and click the cube. The color will change.

7. Adding UI

Let’s add UI to the game to display information to the user.

7.1 Creating a UI Canvas

  1. Right-click in the Hierarchy Panel and select “UI” > “Canvas” to create a canvas.
  2. Add “Text” under the canvas to enter the game title or instructions.

7.2 Styling the UI

You can change font size, color, etc., in the Inspector Panel. Additionally, you can adjust the position and alignment to arrange it nicely.

8. Building and Deploying

Once game development is complete, you can build the outcome for deployment. Let’s move on to the next steps.

8.1 Setting Up Build

  1. Select “File” > “Build Settings” from the top menu.
  2. Select the desired platform and click the “Switch Platform” button.
  3. Click the “Build” button to create the executable file.

8.2 Deployment

The completed game can be deployed according to the platform. For instance, for PC, you distribute the executable file, and for mobile, you package it as an APK file for distribution.

9. Conclusion

In this course, we learned basic concepts of Unity and how to create a simple game. Unity is a very powerful tool, and continuous learning is required to master more complex features and techniques. Utilize various tutorials and resources to explore more functionalities.

10. References

Thank you for reading the Unity course on this blog! We support your Unity learning journey.