📅  最后修改于: 2021-01-11 13:41:10             🧑  作者: Mango
编程中的循环是重复动作的方式。让我们看一下三种不同的循环:For循环,While循环和Do While循环。
?while循环?用于在满足条件时执行操作。
要进行while循环,请从关键字“ while”开始。后跟方括号。在方括号内,您必须写一个条件。只要条件为真,就会执行循环块中的代码:
句法:
while(condition){
//loop block
}
例:
让我们来看一个例子。在此示例中,我们有一个名为PlayerLives的变量。我们总共有一个玩家的四个生命。当玩家的生命数量大于零时,玩家可以玩游戏。意味着,此循环将持续四次,因为玩家有四个生命。之后,玩家将输掉比赛。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WhileLoop : MonoBehaviour
{
int PlayerLives = 4;
void Start()
{
while (PlayerLives > 0)
{
Debug.Log("You have only " +PlayerLives +" Life");
PlayerLives--;
}
Debug.Log("You lost the Game");
}
}
输出:
do-while循环与While循环几乎相同,但有一个主要区别。尽管while循环在循环主体之前测试条件,但是do-while循环在主体结尾测试条件。这种差异意味着do-while循环的主体至少可以运行一次。这是do-while循环的语法:
句法:
do{
//body of a loop
} while(condition);
例:
在此示例中,我们可以看到我们有一个布尔变量,应该称为ShouldContinue。此变量设置为false。接下来,我们有Do while循环。我们以关键字do开头,后跟开括号和闭括号,无论这些括号之间的代码如何构成循环的主体。在正文之后?while关键字?是否有条件。在这种情况下,仅当变量shouldContinue等于true时,循环才会继续。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoWhileLoop : MonoBehaviour
{
void Start()
{
bool shouldContinue = false;
do
{
print("Welcome to the Game");
} while (shouldContinue == true);
}
}
输出:
对于循环?这可能是最常见且最灵活的循环。 for循环?通过创建迭代次数可控制的循环来工作。从功能上讲,它首先检查循环中的条件。在每个循环(称为迭代)之后,可以选择增加一个值。
此语法具有三个参数。第一个是迭代器;这用于计算循环的迭代次数。第二个参数是必须满足的条件,循环才能继续。最后,第三个参数定义每个循环中的迭代器发生什么情况。
句法:
for(int i = 0; i<10; i++){
//loop block
}
例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ForLoop : MonoBehaviour
{
int numEnemies = 3;
void Start()
{
for (int i = 0; i < numEnemies; i++)
{
Debug.Log("Creating enemy number: " + i);
}
}
}
输出:
foreach循环非常简单易用。它具有最简单的语法。在此循环中使用foreach关键字,后跟方括号。您必须在方括号内指定要迭代的数据类型。
选择一个元素变量名称,然后根据需要为该变量命名。该名称用于访问主循环块内的此变量。在名称之后,输入一个关键字,然后输入我们的List变量名称。
句法:
foreach(Type element name in myCollectionVariable){
//block of code
}
例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ForEachLoop : MonoBehaviour
{
void Start()
{
string[] names = new string[3];
names[0] = "JavaTpoint";
names[1] = "Nikita";
names[2] = "Unity Tutorial";
foreach (string item in names)
{
print(item);
}
}
}
输出: