[英]Unity 3D: For looping C#
My Code work properly, but i need to limiting the prefab to 5 times only. 我的代码可以正常工作,但我需要将预制件限制为5次。 I want to using for loop..... 我想使用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 );
}
}
Avoid using the functions like Invoke
or InvokeRepeating
. 避免使用Invoke
或InvokeRepeating
类的函数。 Since you refer to a function by its name , if you change it, the string in the Invoke call won't update. 由于您通过函数名称来引用函数,如果您对其进行更改,则Invoke调用中的字符串将不会更新。 Moreover, The Instant_
method will be called uselessly until you change scene or quit game with the method of @bismute. 此外,在您使用Instant_
方法更改场景或退出游戏之前, Instant_
方法将被无用地调用。
I suggest you using coroutines. 我建议您使用协程。 And bonus, you will use a foor loop ! 另外,您将使用foor循环! ;D ; 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 ;
}
}
Is there any reason for using 'for' statement? 有什么理由使用“ for”语句吗? How about this? 这个怎么样?
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 );
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.