在Unity 2D中产生敌人2D
我想让我的敌人在旋转的同时使用'spawn'从顶部出现。在Unity 2D中产生敌人2D
但我收到此错误:
IndexOutOfRangeException: Array index is out of range. spawnScript.addEnemy() (at Assets/Scripts/spawnScript.cs:21)
下面是我的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnScript : MonoBehaviour {
public Transform[] spawnPoints;
public GameObject enemy;
public float spawnTime = 5f;
public float spawnDelay = 3f;
// Use this for initialization
void Start() {
InvokeRepeating ("addEnemy", spawnDelay, spawnTime);
}
void addEnemy() {
// Instantiate a random enemy.
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
// Update is called once per frame
void Update() {
}
}
这是问题所在:public Transform[] spawnPoints;
spawnPoints
变量被宣布为公共,这意味着您要通过编辑器填充它。你没有做到这一点,尺寸仍然是。当尺寸为0
时,Random.Range
将执行此操作Random.Range(0,0)
并将返回0
。当您以0
作为spawnPoints
变量的索引时,它会抛出该错误,因为spawnPoints
中没有任何内容。您必须设置大小。
这是它看起来像现在:
这是它应该是这样的:
注意我是如何拖着变换为spawnPoints
阵列插槽在我的第二个截图上。如果你不这样做,期望得到NullException
错误。
如果您不想在没有设置尺寸的情况下得到该错误,请在使用前检查它是否为spawnPoints.Length > 0
。
if (spawnPoints.Length > 0)
{
int spawnPointIndex = UnityEngine.Random.Range(0, spawnPoints.Length);
Instantiate(enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
通过使spawnPoints
一个public
假设你想从编辑器中设置的size
。您还可以设置从脚本size
但要一个private
可变第一,这样你就不会遇到问题:
void Start()
{
//Set the size to 3 then fill it up
spawnPoints = new Transform[3];
spawnPoints[0] = yourPint1;
spawnPoints[1] = yourPint2;
spawnPoints[2] = yourPint3;
}
错误在这里 - int spawnPointIndex = Random.Range(0, spawnPoints.Length);
你应该写 - Random.Range(0, spawnPoints.Length - 1)
亲爱的,我已经修改了我的剧本,仍然出现同样的错误。你对我的脚本错误有任何其他想法吗?谢谢! :) –
@dlarukov它与Random.Range无关,并且提供'spawnPoints.Length'实际上是正确的方式,而不是'spawnPoints.Length-1',因为Random函数的第二个参数是排他性的。 – Programmer
谢谢!我修改了我的剧本,但我收到了这些2个错误: 断言失败:TLS分配器ALLOC_TEMP_THREAD,底层分配器ALLOC_TEMP_THREAD有unfreed分配 UnityEditor.AssetModificationProcessorInternal:OnWillSaveAssets(字符串[],字符串[],字符串[],Int32)将 资产/脚本/ spawnScript.cs(18,20):错误CS0029:不能隐式地将类型'字符串'转换为'UnityEngine.Transform' –
嗨,没有什么复杂的我的答案。你甚至不需要修改你的代码,所以使用你的问题的原始代码。 **只需在我的答案中改变第二张截图中的尺寸。**。 – Programmer
嗨,我明白了:)谢谢!但是我的敌人看起来是1而且是静态的。但是,我可以看到克隆人在那里,但他们没有出现在我的游戏中。你有什么想法吗? –