在Unity中组合函数
本文关键字:函数 组合 Unity | 更新日期: 2023-09-27 18:21:57
我有两个创建球的函数。一个每1秒产生一个蓝色球,另一个每4秒产生一个红色球。我想把它们加在一起。因为如果游戏结束的动作是一样的,我实际上不需要2个函数。那么,我如何将这些组合在一个函数中呢。
void Start ()
{
StartCoroutine(CreateBall());
StartCoroutine(CreateBall_Red());
gameOver = false;
}
IEnumerator CreateBall()
{
while(true)
{
GameObject particlePop1 = (GameObject)GameObject.Instantiate(ball);
particlePop1.transform.position = new Vector3(Random.Range(-9f, 9f), 6,0);
yield return new WaitForSeconds(1);
if (gameOver)
{
//restartText.text = "Press 'R' for Restart";
//restart = true;
break;
}
}
}
IEnumerator CreateBall_Red()
{
while(true)
{
GameObject particlePop1 = (GameObject)GameObject.Instantiate(ball_Red);
particlePop1.transform.position = new Vector3(Random.Range(-9f, 9f), 6,0);
yield return new WaitForSeconds(4);
if (gameOver)
{
break;
}
}
}
在两个函数中进行此更改
if (gameOver)
{
//restartText.text = "Press 'R' for Restart";
//restart = true;
yield return new WaitForSeconds(0);
break;
}
else
{
yield return new WaitForSeconds(4);// For blue ball yield return new WaitForSeconds(1);
}
您可以制作一个带有两个参数的函数:
IEnumerator CreateBall(GameObject prefab, float waitTime)
{
while(true)
{
GameObject particlePop1 = (GameObject)GameObject.Instantiate(prefab);
particlePop1.transform.position = new Vector3(Random.Range(-9f, 9f), 6,0);
yield return new WaitForSeconds(waitTime);
// Other stuff here
}
}
然后简单地调用:
StartCoroutine(CreateBall(ball, 1));
StartCoroutine(CreateBall(ball_Red, 4));
使其更加灵活!