Unity Basic Course: Conditional Statements – if

Unity is a very important engine in game development, and coding is also essential for implementing game logic. In this tutorial, we will explore how to use the if statement, a conditional statement in Unity using C#, along with various examples of its applications.

Basic Concept of Conditional Statements

A conditional statement is a structure that controls the flow of a program, executing different commands based on whether a given condition is true or false. In C#, conditional statements are primarily implemented using the if statement.

Basic Syntax of the if Statement

if (condition) {
        // Code to execute when condition is true
    }

In the above syntax, the ‘condition’ part is a Boolean expression that should return true or false. The code inside the curly braces is executed only when the condition is true.

Example of Using the if Statement

Below is a basic example of using the if statement in a Unity script.

Example 1: Checking Player’s Health

using UnityEngine;

    public class Player : MonoBehaviour {
        public int health = 100;

        void Update() {
            if (health <= 0) {
                Debug.Log("The player has died.");
            }
        }
    }

In this example, the Update method is called every frame. If the player’s health drops to 0 or below, a message saying “The player has died.” will be logged.

Using the else Statement

By using the else statement in conjunction with the if statement, you can specify the code that will be executed if the condition is false.

using UnityEngine;

    public class Player : MonoBehaviour {
        public int health = 100;

        void Update() {
            if (health <= 0) {
                Debug.Log("The player has died.");
            } else {
                Debug.Log("The player is healthy.");
            }
        }
    }

Nested if Statements

Conditional statements can be nested, allowing for more complex logic. The following example checks both the player’s health and their weapon status.

using UnityEngine;

    public class Player : MonoBehaviour {
        public int health = 100;
        public bool hasWeapon = false;

        void Update() {
            if (health <= 0) {
                Debug.Log("The player has died.");
            } else {
                if (hasWeapon) {
                    Debug.Log("The player is equipped with a weapon.");
                } else {
                    Debug.Log("The player is not equipped with a weapon.");
                }
            }
        }
    }

Using else if Statements

You can use else if to handle multiple conditions, allowing you to process various cases simultaneously.

using UnityEngine;

    public class Player : MonoBehaviour {
        public int health = 100;

        void Update() {
            if (health > 75) {
                Debug.Log("The player is healthy.");
            } else if (health > 50) {
                Debug.Log("The player is tired.");
            } else if (health > 25) {
                Debug.Log("The player is in danger.");
            } else {
                Debug.Log("The player has died.");
            }
        }
    }

Using Logical Operators in Conditional Statements

Conditional statements can use logical operators such as AND (&&) and OR (||). You can combine multiple conditions to create more complex conditions.

Using the AND Operator

using UnityEngine;

    public class Player : MonoBehaviour {
        public int health = 100;
        public bool hasWeapon = true;

        void Update() {
            if (health > 0 && hasWeapon) {
                Debug.Log("The player is alive and has a weapon.");
            } else {
                Debug.Log("The player is in a dangerous state.");
            }
        }
    }

Using the OR Operator

using UnityEngine;

    public class Player : MonoBehaviour {
        public int health = 100;
        public bool hasWeapon = false;

        void Update() {
            if (health <= 0 || !hasWeapon) {
                Debug.Log("The player has died or does not have a weapon.");
            } else {
                Debug.Log("The player is alive and has a weapon.");
            }
        }
    }

Conclusion

In this tutorial, we have thoroughly explored how to use the if statement in Unity. Conditional statements are very important in controlling the game’s logic, and to create complex games, one must be able to utilize various conditional statements. Make sure to implement if, else, else if, and logical operators appropriately to create your own game logic. Solidify your foundation in Unity and strive to grow into a more advanced game developer.

Unity Basics Course: First-Person View and Rotation Function

Unity is a powerful engine that innovatively changes many aspects of modern game development. In this course, we will explain in detail how to implement a first-person perspective and add a rotation feature within that perspective. This will provide an opportunity to create your first gameplay experience in Unity.

1. Installing Unity and Basic Setup

To use Unity, you must first download and install the Unity Hub from the official website. After installation, create a new project and select the “3D” template. The 3D template is suitable for creating perspective-based games like first-person views.

2. Setting Up the First-Person Character Controller

To implement a first-person game in Unity, you need to set up a character controller. This allows the player to explore the game environment. Proceed to the next steps.

2.1 Adding the Character Controller

Right-click in the Hierarchy window of the project and select “3D Object” > “Capsule” to create a capsule. This will be used as the player. Rename the capsule to ‘Player’.

2.2 Adding a Camera

To create an actual first-person view, you need to add a camera on top of the capsule. Select the Player object, right-click, and choose “Camera” to add the camera. The camera should be placed as a child of the Capsule object.

2.3 Adjusting Camera Position

Adjust the camera’s position to match the player’s head height. Generally, set the Y-axis value to 1.5. Use the Transform component to adjust the camera’s position.

3. Implementing Rotation Functionality

Now let’s add the rotation functionality so the player can adjust the view direction. To do this, you need to write a C# script.

3.1 Creating a New Script

Right-click in the Project window and select “Create” > “C# Script” to create a new script and name it “PlayerController”. Drag this script onto the Player object to add it.

3.2 Writing the Script Content

Open the PlayerController script and write the following code to implement the player’s movement and rotation features:

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

public class PlayerController : MonoBehaviour
{
    public float speed = 5.0f;
    public float sensitivity = 2.0f;

    private float rotationY = 0.0f;

    void Update()
    {
        // Rotation
        float mouseX = Input.GetAxis("Mouse X") * sensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

        rotationY -= mouseY;
        rotationY = Mathf.Clamp(rotationY, -90f, 90f); // Limiting view

        Camera.main.transform.localRotation = Quaternion.Euler(rotationY, 0, 0);
        transform.Rotate(Vector3.up * mouseX);

        // Movement
        float moveX = Input.GetAxis("Horizontal");
        float moveZ = Input.GetAxis("Vertical");
        Vector3 move = transform.right * moveX + transform.forward * moveZ;
        CharacterController controller = GetComponent();
        controller.Move(move * speed * Time.deltaTime);
    }
}

            

3.3 Explanation of the Script

The above code implements the following functionalities:

  • Mouse Input: Calculates rotation based on mouse movement.
  • Vertical and Horizontal Input: Adjusts the player’s position through WASD key input.
  • CharacterController: Uses Unity’s CharacterController for physical collision handling while moving.

4. Physics Settings and Improvements

Now that the basic first-person player controller is complete, let’s address a few improvements and physics settings.

4.1 Adjusting Gravity

You need to add gravity using the CharacterController. Add gravity and jump functionality in the PlayerController script:

private Vector3 velocity;

void Update()
{
    ...
    // Adding gravity
    if (controller.isGrounded)
    {
        velocity.y = -0.5f;
    }
    else
    {
        velocity.y += Physics.gravity.y * Time.deltaTime;
    }
    controller.Move(velocity * Time.deltaTime);
}

            

4.2 Adding Jump Functionality

To implement jumping, you should detect space key input so that the player can jump. Add the following code.

if (Input.GetButtonDown("Jump") && controller.isGrounded)
{
    velocity.y = Mathf.Sqrt(jumpHeight * -2f * Physics.gravity.y);
}

            

4.3 Visual Improvements

To create a more natural camera perspective, it’s a good idea to add animations for when the player moves. Consider using Animator and Animation Clip for this purpose.

5. Additions and Optimization

To enhance the player’s sensory experience, consider the following additions.

5.1 Adding Sound Effects

Adding sounds for movement and jumping can increase immersion. Learn how to add sounds using the AudioSource component.

5.2 Using Canvas for Interface and HUD Configuration

Add a UI Canvas to provide essential information to the player. The HUD can display health, mini-maps, scores, etc.

5.3 Optimization

To prevent performance degradation of assets or scripts, analyze and optimize performance using the Profiler. Monitor Unity’s memory usage and CPU usage to adjust to optimal conditions.

Conclusion

Through this course, we have learned about the basic implementation of a first-person perspective and rotation functionality in Unity. Based on this foundational knowledge, try using your creativity to create various games.

Unity is a platform with endless possibilities. Enhance your abilities in Unity through practice and experimentation. We will learn about various features and advanced game development processes in future courses. Happy developing!

Unity Basics Course: Creating an Ending Screen

In this course, we will learn how to create an ending screen for a game using Unity. The ending screen is an important element that indicates to the player that they have completed the game and it is necessary to convey the theme of the game well. Each step will be explained in detail, along with necessary code examples.

1. Understanding the Components of the Ending Screen

The ending screen consists of various elements, which reflect the game’s story and mood. Generally, the following elements are included:

  • Game Logo: A graphic representing the identity of the game.
  • Thank You Message: An expression of gratitude for the player’s participation.
  • Restart Button: An option for the player to restart the game.
  • Exit Button: An option to exit the game.
  • Ranking or Score: Space to display the player’s achievements.

2. Setting Up a Unity Project

The first step is to create a new Unity project. Launch Unity and follow the steps below to set up a new 2D project:

  1. Run the Unity Hub and click the ‘New Project’ button.
  2. Select the ‘2D’ template and enter a project name.
  3. Specify the saving location of the project and click the ‘Create’ button.

3. Designing the UI of the Ending Screen

To design the ending screen in Unity, you need to add UI elements. Follow the steps below to set up the UI:

  1. Right-click in the Hierarchy window and select ‘UI > Canvas’ to create a canvas.
  2. Under Canvas, select ‘UI > Image’ to add a background image. Adjust the ratio to fill the whole screen.
  3. Set the background color or drag an image file to use as the background.

Now let’s add text and buttons:

  1. Under Canvas, select ‘UI > Text – TextMeshPro’. Create a text object and enter the title (e.g., “Game Completed!”).
  2. Adjust the text properties to set the size and color.
  3. Similarly, add ‘UI > Button’ and set the button’s text to “Restart” or “Exit”.

4. Writing the UI Script for the Ending Screen

Now, let’s write a script to make the ending screen functional. Create a new C# script and name it ‘EndingScreen’, then write the following code:

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

public class EndingScreen : MonoBehaviour
{
    public Button restartButton;
    public Button exitButton;

    void Start()
    {
        restartButton.onClick.AddListener(RestartGame);
        exitButton.onClick.AddListener(ExitGame);
    }

    void RestartGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
    }

    void ExitGame()
    {
        Application.Quit();
    }
}
    

Add the script you wrote to the Canvas of the ending screen, and assign the functions related to the buttons.

5. Integrating Game Logic with the Ending Screen

Now, you need to modify the game logic so that the ending screen appears when the game is over. Add the following code to call the ending screen at the last state of the game:

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public GameObject endingScreen;

    public void GameOver()
    {
        endingScreen.SetActive(true);
    }
}
    

Now, set the game over conditions and assign the ending screen’s Canvas to the endingScreen variable so that the ending screen is displayed when the game is over.

6. Adding Animation to the Ending Screen

You can add animation effects to the ending screen to provide a more engaging user experience. You can add animations using the following methods:

  1. Select the ending screen Canvas and click ‘Add Component’. Add an ‘Animator’.
  2. Create an ‘Animation’ folder in the Project window, and in that folder, select ‘Create > Animation’ to create a new animation.
  3. In the Animation window, click ‘Add Property’ and add the desired properties, such as color or position. Then link this animation to Animate the End Game Canvas.

7. Final Check and Build

After completing all the setups, play the game to check if the ending screen works correctly. If there are no issues, prepare to build the game. Select the platform to build and run:

  1. Select ‘File > Build Settings’ in the top menu.
  2. Select the platform and click the ‘Build’ button to start the build process.

Conclusion

In this course, we looked at the process of creating a simple ending screen using Unity. The ending screen of a game is an important element that leaves a deep impression on the player, so it should always be taken care of. By applying various UI designs and animations, create your unique ending screen.

Through this course, I hope you have not only improved your fundamental understanding of Unity but also your understanding of game components. I encourage you to learn many features and techniques through more diverse Unity courses in the future!

Unity Basics Course: Applying Animation

Unity is a powerful game engine used in the game development process. In this tutorial, we will take a detailed look at how to apply animations in Unity. Animation is an essential element to enhance the immersion of the game and make the character’s actions more vivid. This article will discuss a fundamental understanding of Unity’s animation system and how to apply it in depth.

1. Understanding the Basics of Animation

Animation is a technique that expresses motion or change by altering multiple images or objects over time. In Unity, this is implemented by changing the properties of objects (position, rotation, scale, etc.). Unity’s animation system consists of the Animation component and the Animator component. These two components allow you to manage and play animations.

2. Basic Components of Animation

2.1 Animation Clip

An animation clip is data that defines how an object changes over a specific period. Each clip consists of one or more keyframes, and each keyframe represents the state of the object at a specific point in time.

2.2 Animator Controller

The animator controller is used to manage and transition between animation clips. You can create a state machine by linking multiple animation clips and control the transitions of animations based on conditions.

2.3 Animator

The animator component is added to game objects to play the animations of that object. When you add an animator to a game object, the animation clips set in the animator controller will play.

3. Applying Animation in Unity

3.1 Setting Up the Project

To apply animations, you first need to set up a Unity project. Create a new Unity project and select the appropriate mode, either 3D or 2D. After setting up the basic environment, prepare the model to which the animation will be applied.

3.2 Creating an Animation Clip

After preparing the model, let’s look at how to create an animation clip. Follow these steps to create an animation clip:

  1. Select the model to which you want to apply the animation in the Hierarchy window.
  2. Select Window > Animation > Animation from the top menu to open the Animation window.
  3. Click the Create button in the Animation window, and a popup will appear to create a new animation clip. Enter the desired name to save it.
  4. Once the animation clip is created, you can add keyframes to the Timeline to define the animation.

3.3 Adding Keyframes

Here’s how to define an animation by adding keyframes:

  1. In the Animation window, click the timeline of the clip to focus on the necessary time.
  2. Change the properties of the model (position, rotation, scale, etc.) and then click the Add Property button to add the modified properties.
  3. To save the changed values as keyframes, right-click at the corresponding point in the Timeline and select Add Keyframe.
  4. You can complete the desired animation actions in this manner.

3.4 Setting Up the Animator Controller

Now, with the animation clip ready, it’s time to set up the animator controller. The animator controller controls the transitions between each animation clip.

  1. Right-click in the Project window and select Create > Animator Controller.
  2. Double-click the created animator controller to open the Animator window.
  3. Drag and drop Animation clips into the Animator window to add animation clips.
  4. After adding multiple animation clips, set transition conditions to ensure smooth transitions between animations.

4. Testing the Animation

Now that all settings are complete, you can test the animation. Select the game object with the added animator and click the Play button at the bottom to run the animation. Confirm that the animation works correctly.

5. Controlling Animation Transitions and Additional Features

5.1 Controlling Animation Transitions

When the character moves within the game, the animation should transition smoothly. To do this, you need to set the transition conditions appropriately. You can use Blend Trees for this purpose. A Blend Tree allows for harmonious combinations of multiple animation clips to enable natural transitions.

5.2 Utilizing Parameters

If you define parameters in the animator controller, you can control animation transitions based on specific conditions. For example, you can change the animation depending on whether the character is running or jumping. To define these parameters:

  1. Select the Parameters tab in the Animator window.
  2. Press the New button to add the desired type of parameter (boolean, float, integer, etc.).
  3. You can set conditions during the animator’s animation transitions to switch animations based on the defined parameters.

6. Conclusion

In this tutorial, we introduced the basic ways to apply animations in Unity. We learned how to create animation clips, set up the animator controller, and control animation transitions. Animation is a crucial element in game development, so it’s important to enhance your skills through various practical exercises. Mastering Unity’s animation system can significantly increase the immersion of your game.

Additionally, in the next tutorial, we will explore more advanced animation techniques and methods to control animations using scripts. Continue learning through these Unity foundational tutorials for more insights!

Unity Basic Course: Common Errors, Missing

Unity is a powerful tool for game development, but it comes with many challenges for beginners. Among these, the ‘Missing’ error is one of the common issues encountered when starting a project. In this tutorial, we will explain the causes and solutions for the ‘Missing’ error in detail. This will provide an opportunity to use Unity more effectively and help developers avoid such errors.

1. Definition of Missing Error

The ‘Missing’ error usually occurs due to incorrect file references or incomplete settings in Unity. It primarily happens in the following cases:

  • When a resource file has been deleted or moved
  • When scripts or assets are not properly linked
  • When class names or paths are incorrect in a script

These errors may be displayed as warning messages during game execution or may manifest as problems when using specific assets. For example, the MissingReferenceException error occurs when the referenced object does not exist.

2. Types and Causes of Missing Error

2.1 Missing Script Error

The Missing Script error primarily occurs when the script file assigned to a game object has been deleted or moved. In such cases, the developer can verify that ‘Missing (Mono Script)’ is displayed in the script component area when selecting the object in the editor.

2.2 Missing Asset Error

The Missing Asset error appears when the file cannot be found in the project’s path. If an asset has been moved to an incorrect path, Unity will no longer be able to find that file through the original path. This can occur with various files including scripts, meshes, and textures.

2.3 Missing Prefab Error

A Prefab is a template for reusable game objects in Unity. If a Prefab is deleted or the associated script does not exist, the Missing Prefab error will occur in all game objects that use that Prefab.

3. Solutions for Missing Error

3.1 Reconnecting Scripts

To resolve the Missing Script error, follow these steps:

  1. Select the game object.
  2. In the Inspector panel, find the ‘Missing (Mono Script)’ component and click the ‘Add Component’ button.
  3. Find and add the required script.

3.2 Checking and Restoring File Paths

To resolve the Missing Asset error, follow these procedures:

  1. Check the path where the asset is located. Verify if the file has been moved within the project.
  2. If the file has been deleted, restore it from a backup or recreate it.
  3. Correct any incorrect paths in the scripts that use the resource.

3.3 Modifying and Connecting Prefabs

The Missing Prefab error can be resolved as follows:

  1. Check the Prefab again, and recreate it if necessary.
  2. Explore the hierarchy of the game objects that are missing the Prefab.
  3. Locate the mentioned Prefab and reconnect it.

4. How to Prevent Missing Errors

4.1 Managing Project Structure

Maintaining a consistent project structure makes it easy to locate each file. It is advisable to organize folders systematically and clean up unused files.

4.2 Using Version Control Systems

Using version control systems like Git can prevent files from being improperly changed or deleted. You can restore to a previous state at any time, making it very useful.

4.3 Regular Project Backups

Regularly backing up your project can prevent data loss. If assets or scripts are deleted or corrupted, it is much easier to restore files from a backup.

5. Summary

The ‘Missing’ error that occurs in Unity can be caused by various factors, and it is important to clearly identify the location and cause of the error in order to resolve it. Through the content discussed in this tutorial, I hope it helps you understand and efficiently resolve such errors.

6. References