Loops
Проверено с версией:: 4
-
Сложность: Базовая
How to use the For, While, Do-While, and For Each Loops to repeat actions in code.


Loops
Базовая Scripting
ForLoop
Code snippet
using UnityEngine;
using System.Collections;
public class ForLoop : MonoBehaviour
{
int numEnemies = 3;
void Start ()
{
for(int i = 0; i < numEnemies; i++)
{
Debug.Log("Creating enemy number: " + i);
}
}
}
#pragma strict
var numEnemies : int = 3;
function Start ()
{
for(var i : int = 0; i < numEnemies; i++)
{
Debug.Log("Creating enemy number: " + i);
}
}
import UnityEngine
import System.Collections
public class ForLoop(MonoBehaviour):
private numEnemies = 3
private def Start():
for i in range(0, numEnemies):
Debug.Log(('Creating enemy number: ' + i))
WhileLoop
Code snippet
using UnityEngine;
using System.Collections;
public class WhileLoop : MonoBehaviour
{
int cupsInTheSink = 4;
void Start ()
{
while(cupsInTheSink > 0)
{
Debug.Log ("I've washed a cup!");
cupsInTheSink--;
}
}
}
#pragma strict
var cupsInTheSink : int = 4;
function Start ()
{
while(cupsInTheSink > 0)
{
Debug.Log ("I've washed a cup!");
cupsInTheSink--;
}
}
import UnityEngine
import System.Collections
public class WhileLoop(MonoBehaviour):
private cupsInTheSink = 4
private def Start():
while cupsInTheSink > 0:
Debug.Log('I\'ve washed a cup!')
cupsInTheSink -= 1
DoWhileLoop
Code snippet
using UnityEngine;
using System.Collections;
public class DoWhileLoop : MonoBehaviour
{
void Start()
{
bool shouldContinue = false;
do
{
print ("Hello World");
}while(shouldContinue == true);
}
}
#pragma strict
function Start()
{
var shouldContinue : Boolean = false;
do
{
print ("Hello World");
}while(shouldContinue == true);
}
import UnityEngine
import System.Collections
public class DoWhileLoop(MonoBehaviour):
private def Start():
shouldContinue = false
while true:
print('Hello World')
break unless (shouldContinue == true)
ForeachLoop
Code snippet
using UnityEngine;
using System.Collections;
public class ForeachLoop : MonoBehaviour
{
void Start ()
{
string[] strings = new string[3];
strings[0] = "First string";
strings[1] = "Second string";
strings[2] = "Third string";
foreach(string item in strings)
{
print (item);
}
}
}
#pragma strict
function Start ()
{
var strings = ["First string", "Second string", "Third string"];
for(var item : String in strings)
{
print (item);
}
}
import UnityEngine
import System.Collections
public class ForeachLoop(MonoBehaviour):
private def Start():
strings as (string) = array(string, 3)
strings[0] = 'First string'
strings[1] = 'Second string'
strings[2] = 'Third string'
for item as string in strings:
print(item)
Связанные обучающие материалы
- Arrays (Урок)