我的代码工作正常,但我需要将预制件限制为仅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 );
}
}
答案 0 :(得分:1)
避免使用Invoke
或InvokeRepeating
等功能。由于您通过 name 引用函数,如果更改它,Invoke调用中的字符串将不会更新。此外,在使用@bismute方法更改场景或退出游戏之前,Instant_
方法将被无用地调用。
我建议您使用协同程序。和奖金,你将使用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 ;
}
}
答案 1 :(得分:-1)
有没有理由使用'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 );
}
}
}