2017-11-11 65 views
0

我想讓我的敵人在旋轉的同時使用'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() { 

} 
} 

回答

2

這是問題所在:public Transform[] spawnPoints;

spawnPoints變量被宣佈爲公共,這意味着您要通過編輯器填充它。你沒有做到這一點,尺寸仍然是。當尺寸爲0時,Random.Range將執行此操作Random.Range(0,0)並將返回0。當您以0作爲spawnPoints變量的索引時,它會拋出該錯誤,因爲spawnPoints中沒有任何內容。您必須設置大小。

這是它看起來像現在:

enter image description here

這是它應該是這樣的:

enter image description here

注意我是如何拖着變換爲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; 
} 
+0

謝謝!我修改了我的劇本,但我收到了這些2個錯誤: 斷言失敗:TLS分配器ALLOC_TEMP_THREAD,底層分配器ALLOC_TEMP_THREAD有unfreed分配 UnityEditor.AssetModificationProcessorInternal:OnWillSaveAssets(字符串[],字符串[],字符串[],Int32)將 資產/腳本/ spawnScript.cs(18,20):錯誤CS0029:不能隱式地將類型'字符串'轉換爲'UnityEngine.Transform' –

+0

嗨,沒有什麼複雜的我的答案。你甚至不需要修改你的代碼,所以使用你的問題的原始代碼。 **只需在我的答案中改變第二張截圖中的尺寸。**。 – Programmer

+0

嗨,我明白了:)謝謝!但是我的敵人看起來是1而且是靜態的。但是,我可以看到克隆人在那裏,但他們沒有出現在我的遊戲中。你有什麼想法嗎? –

0

錯誤在這裏 - int spawnPointIndex = Random.Range(0, spawnPoints.Length);

你應該寫 - Random.Range(0, spawnPoints.Length - 1)

+0

親愛的,我已經修改了我的劇本,仍然出現同樣的錯誤。你對我的腳本錯誤有任何其他想法嗎?謝謝! :) –

+1

@dlarukov它與Random.Range無關,並且提供'spawnPoints.Length'實際上是正確的方式,而不是'spawnPoints.Length-1',因爲Random函數的第二個參數是排他性的。 – Programmer