Sharp Coder is reader-supported, meaning when you buy through links on our site, we may earn an affiliate commission.
HomeBlogUnityProgramming

Creating Conditional Statements (If-Else) in Unity Code

0 Comments ยท May 20, 2023
26

The ConditionalStatementsExample script demonstrates the use of conditional statements (if-else) in Unity.

using UnityEngine;

public class ConditionalStatementsExample : MonoBehaviour
{
    int playerScore = 75;
    int passingScore = 60;

    void Update()
    {
        // Check if the player's score is higher than the passing score
        if (playerScore > passingScore)
        {
            Debug.Log("Congratulations! You passed the level.");
        }
        else if (playerScore == passingScore)
        {
            Debug.Log("You just made it to the passing score. Keep going!");
        }
        else
        {
            Debug.Log("Sorry, you didn't reach the passing score. Try again.");
        }
    }
}

How does it work?

  1. The playerScore variable represents the player's score, and the passingScore variable represents the minimum score required to pass.
  2. In the Update() method, we check the player's score against the passing score using conditional statements.
  3. The if statement checks if the player's score is higher than the passing score. If it is, it executes the code block inside the if statement, which logs a congratulatory message to the Unity console.
  4. The else if statement checks if the player's score is equal to the passing score. If it is, it executes the code block inside the else if statement, which logs a message indicating that the player just made it to the passing score.
  5. If none of the previous conditions are met, the else statement executes the code block inside it, which logs a message stating that the player didn't reach the passing score.

Conditional statements allow you to control the flow of your program based on certain conditions. In this case, the messages logged to the console depend on the comparison between the player's score and the passing score.

You can modify the playerScore and passingScore variables to test different scenarios and observe the corresponding messages logged in the console based on the outcome of the conditional statements.

You Do Not Have To Do Everything Yourself
Search from thousands of ready-to-use Unity assets.
Visit Asset Store