同一个对象在C#中一次又一次地实例化

时间:2016-03-19 08:56:19

标签: c# unity5

我是编码的初学者。我一直在尝试重新制作流行的手机游戏“Crossy Road”'几天了当我试图创建一个Level Generation脚本时,我遇到了一个问题。我面临的问题是,当我尝试随机实例化3个不同的对象时(在这种情况下是Grass,Road和Water),只会生成草。如果有人能告诉我为什么它一直在实例化“草”,我会非常感激。反复对象。我正在Unity 5中重新创建游戏。代码如下 -

using UnityEngine;
using System.Collections;

public class LevelGenerationScript : MonoBehaviour {

public GameObject Water;
public GameObject Road;
public GameObject Grass;
int firstRand;
int secondRand;
int distPlayer = 10;

Vector3 intPos = new Vector3(0,0,0);

void Update () 
{
    if (Input.GetButtonDown("up")) 
    {
        firstRand = Random.Range(1,4);
        if(firstRand == 1)
        {
            secondRand = Random.Range(1,8);
            for(int i = 0;i < secondRand; i++)
            {
                intPos = new Vector3(0,0,distPlayer);
                distPlayer += 1;
                GameObject GrassIns = Instantiate(Grass) as GameObject;
                GrassIns.transform.position = intPos;
            }

            if(firstRand == 2)
            {
                secondRand = Random.Range(1,8);
                for(int i = 0;i < secondRand; i++)
                {
                    intPos = new Vector3(0,0,distPlayer);
                    distPlayer += 1;
                    GameObject RoadIns = Instantiate(Road) as GameObject;
                    RoadIns.transform.position = intPos;
                }

                if(firstRand == 3)
                {
                    secondRand = Random.Range(1,8);
                    for(int i = 0;i < secondRand; i++)
                    {
                        intPos = new Vector3(0,0,distPlayer);
                        distPlayer += 1;
                        GameObject WaterIns = Instantiate(Water) as GameObject;
                        WaterIns.transform.position = intPos;
                    }
                }
            }
        }
    }
}
}

如果有人能告诉我这个错误,我真的很感激。 谢谢!

2 个答案:

答案 0 :(得分:1)

您已将其他对象的代码放在firstRand为1时调用的代码组内。(FirstRand == 2)和(FirstRand == 3)处于此位置永远不会出现,您已编写无法访问的代码。

答案 1 :(得分:1)

您的陈述if (firstRand == 2)永远不会被曝光,因为它包含在if (firstRand ==1)声明中。

您需要构建这样的if语句:

if (firstRand == 1)
{
   ...
}

if (firstRand == 2)
{
   ...
}

if (firstRand == 3)
{
   ...
}

如果您想改进代码,以下内容应该有效:

firstRand = Random.Range(1,4);
secondRand = Random.Range(1,8);
GameObject instance = null;

for (int i = 0; i < secondRand; i++)
{
    intPos = new Vector3(0, 0, distPlayer);
    distPlayer += 1;

    switch (firstRand)
    {
        case 1:
            instance = Instantiate(Grass) as GameObject;
            break;
        case 2:
            instance = Instantiate(Road) as GameObject;
            break;
        case 3:
            instance = Instantiate(Water) as GameObject;
            break;
    }

    instance.transform.position = intPos;
}