[英]Unity 2017 - Balloon spawner does not work?
I am programming a 2D platformer where my main sprite jumps on randomly spawned bubbles/balloons. 我正在编写一个2D平台游戏,我的主精灵会跳到随机生成的气泡/气球上。 Below is the code I used.
下面是我使用的代码。 However, no balloons get generated at all but my other features in the game perfectly fine.
但是,除了我在游戏中的其他功能外,根本不会产生气球。
public class spawner2 : MonoBehaviour {
public GameObject[] balloons;
public Vector3 spawnValues;
public float spawnWait;
public float spawnMostWait;
public float spawnLeastWait;
public int startWait;
public bool stop;
int randBalloon;
// Use this for initialization
void Start () {
StartCoroutine (waitSpawner ());
}
// Update is called once per frame
void Update () {
spawnWait = Random.Range (spawnLeastWait, spawnMostWait);
}
IEnumerator waitSpawner()
{
yield return new WaitForSeconds (startWait);
while (true)
{
randBalloon = Random.Range (0, 5);
//float randY = Random.Range(-0.25f,-2.25f);
Vector3 spawnPosition = new Vector3 (Random.Range(-spawnValues.x, spawnValues.x),Random.Range(-spawnValues.y, spawnValues.y),1);
Instantiate ((balloons[randBalloon]),spawnPosition + transform.TransformPoint (0,0,0),gameObject.transform.rotation);
yield return new WaitForSeconds (spawnWait);
}
}
The only error I get is: Press here to view This is what I have in the inspector: The inspector As a beginner in game development and in C# I would appreciate any help. 我得到的唯一错误是: 按此查看检查器中的内容: 检查器作为游戏开发和C#的初学者,我将感谢您的帮助。
The error is pretty straightforward. 该错误非常简单。
Your balloons array contains 2 items, thus it has items in index 0 and index 1. 您的Balloons数组包含2个项目,因此它的索引为0和索引为1。
randBalloon = Random.Range (0, 5);
Generates a random number, ranging from 0 to 4 (the second parameter is an exclusive int). 生成一个随机数,范围从0到4(第二个参数是一个独占int)。
So, your spawner will regulary try to access index 2, 3 and 4 which are all indices that do not exist and therefore results in an index out of range exception. 因此,您的生成器将定期尝试访问索引2、3和4,它们都是不存在的索引,因此会导致索引超出范围异常。
You can easilly fix it by using this: 您可以使用以下方法轻松修复它:
randBalloon = Random.Range (0, balloons.Length - 1);
balloons.Length will return an int of 2 in your case, because it gives you the length of your array. Balloons.Length在您的情况下将返回一个2的int值,因为它为您提供数组的长度。 Since you need 0 to reference the first item of an array and not 1, we add the "-1".
由于您需要0而不是1来引用数组的第一项,因此我们添加“ -1”。 This way, you can never get an index out of range exception.
这样,您将永远无法获得索引超出范围的异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.