Creating Conditional Statements (if-else) in Unity Code
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 Do Conditional Statements Work?
- The playerScore variable represents the player's score, and the passingScore variable represents the minimum score required to pass.
- In the Update() method, we check the player's score against the passing score using conditional statements.
- 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.
- 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.
- 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.
Conclusion
Conditional statements allow to control the flow of the 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.
The playerScore and passingScore variables can be modified to test different scenarios and observe the corresponding messages logged in the console based on the outcome of the conditional statements.