在 Unity 代码中创建条件语句 (if-else)

ConditionalStatementsExample 脚本演示了 Unity 中条件语句 (if-else) 的使用。

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.");
        }
    }
}

条件语句如何工作?

  1. playerScore 变量表示玩家的分数,passingScore 变量表示通过所需的最低分数。
  2. Update() 方法中,我们使用条件语句检查玩家的分数与及格分数。
  3. if 语句检查玩家的分数是否高于及格分数。如果是,它将执行 if 语句内的代码块,该语句将 congratulatory 消息记录到 Unity 控制台。
  4. else if 语句检查玩家的分数是否等于及格分数。如果是,它会执行 else if 语句内的代码块,该语句会记录一条消息,指示玩家刚刚达到及格分数。
  5. 如果前面的条件均不满足,则 else 语句将执行其中的代码块,该代码块会记录一条消息,表明玩家未达到及格分数。

结论

条件语句允许根据某些条件控制程序的流程。在这种情况下,记录到控制台的消息取决于玩家分数和及格分数之间的比较。

可以修改 playerScorepassingScore 变量来测试不同的场景,并根据条件语句的结果观察控制台中记录的相应消息。

推荐文章
Unity C# 中有用关键字列表
Unity状态机简介
Unity 平台特定编译
Unity C# 脚本语言简介
在 Unity 中实现对象池
在 Unity 中创建交互式对象
在 Unity 中实现动力学交互