[英]The Same Object is Getting Instantiated again and again in C#
我是编码的初学者。 我一直在尝试重新创建流行的手机游戏“ Crossy Road”。 当我尝试创建一个关卡生成脚本时,遇到了一个问题。 我面临的问题是,当我尝试随机实例化3个不同的对象(在本例中为“草”,“路”和“水”)时,只会生成草。 如果有人能告诉我为什么它不断重复实例化“ Grass”对象,我将不胜感激。 我正在Unity 5 Fyi中重新创建游戏。 代码如下-
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;
}
}
}
}
}
}
}
如果有人可以告诉我这个错误,我将非常感激。 谢谢!
您已将其他对象的代码放置在firstRand为1时调用的代码组内。(FirstRand == 2)和(FirstRand == 3)在此位置永远都不是,您编写了无法访问的代码。
您的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.