结合Unity中的功能

时间:2014-09-14 07:19:40

标签: c# unity3d monodevelop

我有2个创造球的功能。一个人每1秒创造一个蓝色球,另一个每4秒创造一个红色球。我希望将它们添加到togeteher中。因为如果游戏中的动作是相同的,我实际上不需要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;
        }
    }


}

2 个答案:

答案 0 :(得分:1)

在两个函数中进行此更改

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

答案 1 :(得分:0)

您可以使用两个参数创建单个函数:

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

让它更灵活!