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 Basic Course: Limitations on Up and Down Rotation Angles

In game development, the rotation of the camera or character is a very important element. In particular, limiting the angle during up and down rotation helps enhance the player’s experience in the game. In this tutorial, we will learn how to limit the up and down rotation angle of an object in Unity.

1. Understanding the Basics of Unity

Unity is a powerful engine for developing games and interactive content. Unity primarily uses the C# programming language and offers a user-friendly interface. With Unity, you can easily create both 2D and 3D games.

2. Basics of Rotation

Rotation is performed relative to the object’s local axes, typically using Euler angles or quaternions. Up and down rotation is mainly performed around the X-axis and is used to change the viewpoint of the camera or character.

3. Implementing Limits on Up and Down Rotation Angles

To limit the up and down rotation, you need to perform a few tasks. I will explain step by step.

3.1 Preparing the Rotation Script

First, create a new script in your Unity project. Write the following code in the script.

using UnityEngine;

public class CameraController : MonoBehaviour
{
    public float mouseSensitivity = 100f;
    public Transform playerBody;
    float xRotation = 0f;

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -30f, 30f); // Limit up and down rotation angle

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);
    }
}

3.2 Explaining the Script

  • mouseSensitivity: Adjusts the sensitivity of mouse movement.
  • playerBody: References the character’s body.
  • xRotation: Stores the current up and down angle of the camera.

In this script, xRotation controls the up and down rotation. The Mathf.Clamp() function is used to limit the up and down rotation angle between -30 degrees and 30 degrees.

3.3 Applying the Script

Attach the script you wrote above to the camera object in Unity. Then assign the character’s body connected to the camera to the playerBody field.

4. Testing

Now, when you run the game, you can see the camera rotating up and down as you move the mouse. Check if the angle limit is working properly.

5. Improvements

To refine the up and down rotation limits, you can make a few additional enhancements:

  • Set public variables for the angle limit values so they can be easily adjusted in the inspector.
  • Add a speed adjustment feature to enhance the user experience.

Tip: To make the up and down rotation smooth, you can use the Mathf.Lerp function.

6. Conclusion

In this tutorial, we learned how to limit the up and down rotation angles in Unity. This feature helps make the movement of the camera and character more natural and enhances the immersion in the game. Now you can use these techniques to develop your own games!

7. Additional Resources

If you want more resources related to Unity, please refer to the following links: