Unity四种循环方式

教程地址(观看视频需):

https://unity3d.com/cn/learn/tutorials/topics/scripting/loops?playlist=17117

教程代码实例:

第一种:for循环

using UnityEngine;

using System.Collections;

 publicclass ForLoop : MonoBehaviour

{

    int numEnemies = 3;

    void Start ()

    {

        for(int i = 0; i < numEnemies; i++)

        {

           Debug.Log("Creatingenemy number: "+ i);

        }

    }

}

运行结果为:

Unity四种循环方式_第1张图片

终于把for循环捡回来了!^_^开心(*^▽^*)

第二种While循环:

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--;
        }
    }
}

第三种DoWhile循环:

using UnityEngine;
using System.Collections;

public class DoWhileLoop : MonoBehaviour 
{
    void Start()
    {
        bool shouldContinue = false;
        
        do
        {
            print ("Hello World");
            
        }while(shouldContinue == true);
    }
}

第四种Foreach循环:

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

后面三种都没用过,不过while还是挺简单的。



你可能感兴趣的:(Unity四种循环方式)