Unity 3D:用于循环 C#

Unity 3D: For looping C#

我的代码工作正常,但我只需要将预制件限制为 5 次。 我想使用 for 循环......

using UnityEngine;
using System.Collections;

public class theScript : MonoBehaviour {
    public GameObject prefab1;
    // Use this for initialization
    void Start () {
        InvokeRepeating ("Instant_", 1f, 1f);
    }

    // Update is called once per frame
    void Update () {

    }

    void Instant_(){
        Instantiate (prefab1, transform.position, transform.rotation );
    }
}

使用'for'语句有什么理由吗? 这个怎么样?

using UnityEngine;
using System.Collections;

public class theScript : MonoBehaviour {
    public GameObject prefab1;
    public int FiveTimeCheck;

    // Use this for initialization
    void Start () {
        FiveTimeCheck = 0;
        InvokeRepeating ("Instant_", 1f, 1f);
    }

    // Update is called once per frame
    void Update () {

    }

    void Instant_(){
        if(FiveTimeCheck <= 5)
        {
            FiveTimeCheck += 1;
            Instantiate (prefab1, transform.position, transform.rotation );
        }
    }
}

避免使用InvokeInvokeRepeating等函数。由于您通过 名称 引用函数,因此如果更改它,Invoke 调用中的字符串将不会更新。此外,Instant_方法将被无用地调用,直到您使用@bismute方法切换场景或退出游戏。

我建议你使用协程。额外的好处是,您将使用一个 foor 循环! ;D

using UnityEngine;
using System.Collections;

public class theScript : MonoBehaviour {
    public GameObject prefab1;
    public int MaxInstantiation = 5;

    void Start ()
    {
        StartCoroutine( InstantiatePrefab(1) ) ;
    }

    private IEnumerator InstantiatePrefab( float delay = 1f )
    {
        WaitForSeconds waitDelay = new WaitForSeconds( delay ) ;
        for( int instantiateCount = 0 ; instantiateCount < MaxInstantiation ; ++instantiateCount )
        {
            yield return waitDelay ;
            Instantiate (prefab1, transform.position, transform.rotation ) ;
        }
        yield return null ;
    }
}