Unity Basics Course: Creating Classes

Unity is a powerful engine for game development that uses the C# language to create games. C# supports Object-Oriented Programming (OOP), which helps programmers write code efficiently and in a reusable manner. This article will explain how to create classes in Unity in detail.

1. Understanding C# and Object-Oriented Programming

A class is the fundamental unit of object-oriented programming, defining data and the functions that process that data together. In C#, the following basic concepts exist:

  • Class: A blueprint for creating objects.
  • Object: An instance of a class.
  • Property: Data defined in the class.
  • Method: A function defined in the class.
  • Constructor: A special method that is called when an instance of a class is created.

2. Creating a Unity Project

Before starting to write a class in Unity, you must first create a Unity project. Create a new project in Unity Hub and select the basic 3D template. Once the project is loaded, follow the steps below.

3. Creating a Class

Right-click in the project’s Assets folder and select Create > C# Script to create a new script. Name the script MyFirstClass. Double click on the script to open it in Visual Studio or your preferred code editor.


    using UnityEngine;

    public class MyFirstClass
    {
        // Properties
        public int health;
        public string playerName;

        // Constructor
        public MyFirstClass(string name, int initialHealth)
        {
            playerName = name;
            health = initialHealth;
        }

        // Method
        public void TakeDamage(int damage)
        {
            health -= damage;
            if (health < 0)
                health = 0;

            Debug.Log(playerName + "'s remaining health: " + health);
        }
    }
    

3.1. Class Explanation

In the above code, MyFirstClass is used to manage the player's health and name. The properties are health and playerName, which are initialized through the constructor when creating an instance. The TakeDamage method reduces health when damage is taken and logs the result.

4. Using the Class

To use a class in Unity, you need to create an instance in another script. Let's create an instance of the MyFirstClass class:


    using UnityEngine;

    public class GameManager : MonoBehaviour
    {
        void Start()
        {
            MyFirstClass player = new MyFirstClass("Player1", 100);
            player.TakeDamage(20);
        }
    }
    

4.1. GameManager Class Explanation

GameManager class is a script that inherits from Unity's MonoBehaviour. The Start method is called when the script starts, and here we create an instance of MyFirstClass and call the TakeDamage method to reduce health.

5. Working with the Unity Editor

Now, return to the Unity Editor and add the GameManager script to an empty game object. Create an empty game object and drag the GameManager script onto it. Now, press the play button to check if the player's health is logged correctly.

6. Expanding the Class

Let's expand the class by adding various functionalities. For example, let's add a Heal method so the player can recover health:


    public void Heal(int amount)
    {
        health += amount;
        if (health > 100) // Maximum health is capped at 100
            health = 100;

        Debug.Log(playerName + "'s current health: " + health);
    }
    

6.1. Using the Heal Method

To use the Heal method, we will call it from the GameManager class:


    player.Heal(30);
    

7. Understanding Classes and Inheritance

Inheritance is one of the important concepts in object-oriented programming. You can inherit a class and add new functionalities. For example, let's create a Warrior class that inherits from MyFirstClass:


    public class Warrior : MyFirstClass
    {
        public int attackPower;

        public Warrior(string name, int initialHealth, int initialAttackPower) : base(name, initialHealth)
        {
            attackPower = initialAttackPower;
        }

        public void Attack()
        {
            Debug.Log(playerName + " deals " + attackPower + " damage!");
        }
    }
    

7.1. Using the Warrior Class

Let's create an instance of the Warrior class and call the attack method:


    Warrior warrior = new Warrior("Warrior", 120, 50);
    warrior.Attack();
    

8. Utilizing Classes

The ways to utilize classes in Unity are limitless. For example, enemy characters, weapons, items, etc. can be created as classes, each defining their own properties and methods to express various behaviors.

9. Conclusion

In this tutorial, we explored how to create classes in Unity and the basic principles of object-oriented programming in C#. By utilizing classes, you can write more structured and maintainable code. Continue to understand various classes and inheritance, and enhance your skills when creating games.

10. References

Unity Basics Course: Creating an Ending Screen (Defeat)

In game development, the ending screen is an important element that wraps up the player experience. In this tutorial, we will explain how to create a simple ending screen in Unity, with a focus on implementing the ending screen in the event of a defeat condition.

1. Installing Unity and Setting Up the Project

After installing Unity, create a new 2D or 3D project. Once the basic structure of the game is set up, you need to create a dedicated scene for the ending screen. Here’s how to create a new scene:

  • Select File → New Scene.
  • Save the scene. For example, name it “EndingScreen”.

2. Adding Basic UI Elements

To create the ending screen, you need to add user interface (UI) elements. You can use Unity’s UI system to add buttons, text, and image elements. Follow these steps:

  • Right-click in the Hierarchy window and select UI → Canvas to create a new canvas.
  • Add UI → Panel inside the canvas to create a background.
  • Add UI → Text within the Panel to display the “Game Over” message.
  • Add UI → Button to create a “Restart” button.
  • Adjust the properties of the Text and Button to change their style as desired.

2.1 Adjusting Text Properties

Select the text element and enter an appropriate message in the Text property of the Inspector window. Modify font size, color, etc., to enhance readability.

2.2 Adjusting Button Properties

Set the button text to “Restart” and configure the button to call a specific method upon clicking. To do this, add the method to the On Click() event of the Button component.

3. Setting Defeat Conditions

You need to set defeat conditions in the game to create events that transition to the ending screen. For instance, you can configure it to transition to the ending screen when the player’s health reaches 0.

  • Implement health reduction logic in the Player script.
  • When health reaches 0, call SceneManager.LoadScene("EndingScreen"); to transition to the ending screen.

4. Implementing the Ending Screen Script

The ending screen script will be implemented to restart the game when the button is clicked. Below is an example of a script that manages the ending screen.

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

        public class EndingScreen : MonoBehaviour {
            // Method called when the restart button is clicked
            public void OnRestartButtonClicked() {
                // Restart the game from the first scene
                SceneManager.LoadScene("GameScene");
            }
        }
        
    

5. Connecting Ending Screen UI and Script

Now, you need to add the ending screen script to the ending screen canvas and connect the method to the button’s On Click() area.

  • Select the Panel or Canvas object.
  • In the Inspector window, click “Add Component” and add the “EndingScreen” script.
  • Select the Button object and drag the EndingScreen script into the On Click() event.
  • Select the “OnRestartButtonClicked()” method from the dropdown menu.

6. Final Testing and Improvements

Run the game to check if the ending screen works properly by inducing defeat conditions. Verify that the ending screen appears correctly and that it returns to the game scene when the button is clicked. If necessary, adjust the layout or style of the UI elements for improvements.

6.1 Implementing Additional Features

You can add various features to the ending screen besides statistics, scores, or the restart button. For example, consider adding:

  • Game timer display
  • High score tracking
  • Return to main menu button

Conclusion

In this tutorial, we learned how to create an ending screen in Unity upon defeat. The ending screen leaves an important impression on players and serves to provide feedback on game play. We hope you can enhance the player experience by adding an ending screen to your game.

Unity Basics Course: State Transition Based on Distance

Hello! In this tutorial, we will take a closer look at how to implement state transitions based on distance in Unity. State transitions are a very important concept in game development, making the behaviors and reactions of characters or objects more realistic. In this article, we will explain step by step with practical exercises alongside the theory.

1. What is State Transition?

State transition refers to the process of changing the state of an object. For example, it means transitioning from ‘idle state’ to ‘attack state’ when a player character gets close to an enemy. Such state transitions enhance the immersion of the game and provide players with various experiences.

2. Unity and State Transitions

In Unity, state transitions can be implemented using animations and state machines. A state machine is a useful tool for structuring the logic of states changing based on specific conditions. To implement state transitions, the following steps are necessary.

2.1. Setting Up a Unity Project

  1. Launch Unity Hub and create a new 3D project.
  2. Once the project is created, configure the basic environment.

2.2. Adding a Character Model

Download a character model from the Unity Asset Store or create one yourself and add it to the project.

2.3. Adding Animations

Depending on the model, you need to add animations such as idle, movement, and attack. Animations can be added in Unity’s Animation window.

3. Implementing Distance-Based State Transition

Now, let’s implement the core of state transitions: distance-based transitions. To do this, we will write a C# script to calculate the distance between the character and the enemy, and transition states accordingly.

3.1. Writing the C# Script

using UnityEngine;

public class PlayerState : MonoBehaviour
{
    public float detectionDistance = 5.0f;
    public Transform enemy; // Enemy's position

    private enum State
    {
        Idle,
        Attack
    }

    private State currentState = State.Idle;

    void Update()
    {
        float distance = Vector3.Distance(transform.position, enemy.position);
        
        // Distance check
        if (distance < detectionDistance)
        {
            SwitchState(State.Attack);
        }
        else
        {
            SwitchState(State.Idle);
        }
    }

    private void SwitchState(State newState)
    {
        if (currentState != newState)
        {
            currentState = newState;

            switch (currentState)
            {
                case State.Idle:
                    // Actions for Idle state
                    Debug.Log("Idle state");
                    break;
                case State.Attack:
                    // Actions for Attack state
                    Debug.Log("Attack state");
                    break;
            }
        }
    }
}

This script calculates the distance to the enemy and transitions the state. In the Update function, the distance is measured every frame, and if an enemy comes within the set distance, it transitions to the attack state.

3.2. Applying the Script

Attach the created script to the player character and assign the enemy object. When an enemy enters the set distance, the attack animation will be executed.

4. Animation State Transition

Once state transitions are enabled, let’s apply animation transitions. In Unity, we can easily implement transitions between animations using Animator.

4.1. Setting Up the Animator

Add animations to the Animator component of the character and set parameters to transition based on the state. Connect the idle and attack animations in between to ensure that the required animations are referenced.

4.2. Adding Animation Parameters

using UnityEngine;

public class PlayerAnimator : MonoBehaviour
{
    private Animator animator;
    
    void Start()
    {
        animator = GetComponent();
    }

    private void SwitchState(State newState)
    {
        if (currentState != newState)
        {
            currentState = newState;

            switch (currentState)
            {
                case State.Idle:
                    animator.SetBool("isAttacking", false);
                    break;
                case State.Attack:
                    animator.SetBool("isAttacking", true);
                    break;
            }
        }
    }
}

This way, animations will also transition based on the state, providing a more realistic playing experience.

5. Additional Tips

When implementing distance-based state transitions, consider the following tips:

  • Add various behavior patterns for enemies to prompt player reactions.
  • Adding effects during state transitions provides a more immersive experience.
  • Consider allowing the player to transition states based on factors other than distance (e.g., line of sight, speed, etc.).

Conclusion

Through this tutorial, you learned the basic method of implementing state transitions based on distance in Unity. With this foundation, you can create more complex systems and maximize the fun of the desired game. I hope to see you develop more features through future practices. See you in the next tutorial!

Unity Basics Course: Preventing Duplicates in Sound and Scene Transitions

Date: October 10, 2023

Author: [Author Name]

1. What is Unity?

Unity is a powerful game engine for 2D and 3D game development. It supports deployment to various platforms and provides an intuitive user interface along with strong community support. Developers can use Unity to create almost any type of game and interactive content they can imagine.

2. The Importance of Sound

Sound is a very important element in game development. It enhances the mood and immersion of the game and has a significant impact on players’ emotions. Therefore, effectively managing sound effects and background music is key to successful game development.

3. Managing Sound in Unity

3.1 Audio Source and Audio Listener

In Unity, the AudioSource and AudioListener components are used to implement sound. The AudioSource is responsible for playing actual sounds, while the AudioListener receives the sound. Typically, an AudioListener is added to the camera.

3.2 Preparing Audio Clips

After preparing the audio clips to be used in the game, they are added to the project’s Assets folder. Audio clips can be imported in formats such as WAV and MP3. Unity supports various audio formats, and properties of each clip can be adjusted to set the volume, pitch, and more.

4. Preventing Sound Overlap During Scene Transitions

4.1 Basic Theory

When transitioning between scenes in a game, if the audio source from the previous scene continues to play in the new scene, unnecessary overlapping sounds can occur. Various methods can be used to solve this problem.

4.2 Managing Audio with the Singleton Pattern

To prevent sound overlap, the Singleton pattern is commonly used to manage an audio manager. The audio manager consistently manages sounds throughout the game to ensure that sounds do not overlap during scene transitions.

4.2.1 Writing the Audio Manager Script

                
                using UnityEngine;

                public class AudioManager : MonoBehaviour
                {
                    private static AudioManager instance;
                    public AudioSource audioSource;

                    void Awake()
                    {
                        if (instance == null)
                        {
                            instance = this;
                            DontDestroyOnLoad(gameObject); // Prevent destruction during scene transitions
                        }
                        else
                        {
                            Destroy(gameObject); // Destroy existing instance
                        }
                    }

                    public void PlaySound(AudioClip clip)
                    {
                        if (audioSource.isPlaying)
                        {
                            audioSource.Stop();
                        }
                        audioSource.clip = clip;
                        audioSource.Play();
                    }
                }
                
            

4.2.2 Adding the Audio Manager to a Scene

Create a GameObject with the AudioManager script and place it in the game’s first scene. This object will not be destroyed during scene transitions and will handle sound management.

4.3 Implementing Sound Overlap Prevention

When playing sounds in a scene, you can prevent overlapping sounds by calling the AudioManager’s PlaySound method. If you wish to play an audio clip from game objects or other scripts, ensure to reference the AudioManager instance to play the sound.

5. Managing Scene Transitions in Unity

5.1 Methods of Scene Transition

Unity allows easy management and transitioning between multiple scenes. Using the SceneManager, scenes can be loaded effortlessly. Parameters can also be passed or copied during scene transitions.

5.2 Adding Animation During Scene Transitions

Adding animation effects during scene transitions enhances the user experience. Unity’s animation system can be used to implement smooth scene transitions.

6. Conclusion

This tutorial explained how to effectively manage sound in Unity and prevent redundancy during scene transitions. Sound and scene management are crucial elements that enhance the quality of a game, so it’s advisable to find optimized methods for your game through sufficient practice and research. The next tutorial will cover more diverse Unity techniques.

Unity Basics Course: Adjusting Game Screen Resolution

In game development, screen resolution is an important factor that significantly affects the user’s gaming experience. If the resolution is not properly adjusted, the screen may appear torn or stretched, which can negatively impact the immersion of the game. In this article, we will take a closer look at how to adjust the game screen resolution in Unity.

1. Understanding Resolution

Resolution refers to the number of pixels displayed on the screen, typically expressed in the form of width x height in pixels. For example, a resolution of 1920×1080 means a screen with 1920 pixels in width and 1080 pixels in height. Higher resolution provides more detail and sharper images, but it also consumes more system resources.

2. Resolution Settings in Unity

Unity offers several ways to set resolution. It provides various features to adjust the resolution according to different platforms, so understanding this is necessary.

2.1. Setting Game Window Resolution

To set the resolution in Unity’s game view, follow these steps:

  1. Select ‘Window’ -> ‘General’ -> ‘Game’ from the top menu of the Unity Editor.
  2. Find the resolution dropdown menu in the upper right corner of the game view.
  3. Select a default resolution option or click ‘Add Resolution…’ to add a custom resolution.

2.2. Changing Resolution in Build Settings

You can change the resolution when building the game:

  1. Select ‘Build Settings’ from the File menu.
  2. Choose the target platform and then click ‘Player Settings…’.
  3. In the Inspector window, find the ‘Resolution and Presentation’ section.
  4. Here, you can set the resolution and screen mode (fullscreen, windowed, etc.).

3. Adjusting UI for Different Resolutions

Adjusting UI elements to match the game screen’s resolution is very important. Unity provides the ‘Canvas Scaler’ component that helps display UI elements appropriately across various resolutions.

3.1. Setting Canvas Scaler

To set the Canvas Scaler component:

  1. Select the Canvas object and click the ‘Add Component’ button in the Inspector.
  2. Select ‘Canvas Scaler’ from the ‘UI’ category.
  3. Change the UI Scale Mode to ‘Scale With Screen Size’.
  4. Set the Reference Resolution to your desired resolution and select the appropriate Screen Match Mode.

3.2. Handling Different Aspect Ratios

To ensure the game displays correctly on various aspect ratios, UI elements should be anchored and pivoted for proper placement. This way, the UI layout stays natural even when the resolution or aspect ratio changes.

4. Using Scripts for Resolution Adjustment

Developers can use scripts to dynamically change the resolution. This allows adding functionality to change resolution during game runtime.

4.1. Resolution Change Script


using UnityEngine;

public class ResolutionManager : MonoBehaviour
{
    void Start()
    {
        // Set initial resolution
        Screen.SetResolution(1920, 1080, FullScreenMode.FullScreenWindow);
    }

    public void ChangeResolution(int width, int height)
    {
        Screen.SetResolution(width, height, Screen.fullScreen);
    }
}

The above code sets the default resolution to 1920×1080 when the game starts and shows how to change the resolution using the `ChangeResolution` method.

5. Testing Resolution on Various Devices

Testing different resolutions during game development is essential. It is important to set various resolutions within the Unity Editor to check results or to build and test on actual devices.

5.1. Testing in the Editor

Testing at multiple resolutions in Unity can be easily done by changing the resolution in the ‘Game’ view. After adjusting various settings, check how gameplay performs at each resolution.

5.2. Testing on Actual Devices

For mobile games, it is important to test on actual smartphones and tablets. You should run the game on devices with various screen ratios and resolutions to ensure the UI and graphics display correctly.

6. Optimization Tips

When adjusting the game’s resolution, performance optimization should also be considered. Games that support high resolutions consume more system resources, so here are some tips for optimization.

  • Provide users with the option to select resolution through graphic quality settings.
  • Use aspect ratio-appropriate textures to prevent distortion when adjusting resolution.
  • Set appropriate polygon counts and LOD (Level of Detail) to improve performance.
  • Dynamically load and unload UI elements to save memory.

Conclusion

In this tutorial, we learned about adjusting game screen resolution in Unity and optimization tips. The resolution of the game screen significantly impacts user experience, so developers must carefully consider this. It is essential to test at various resolutions and strive to provide the best experience to users. We hope you can develop high-quality games using Unity’s diverse features.

References