エラー:ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.について
プログラムで以下のエラーが出てしまいます。
対処方法を教えてもらえないでしょうか
エラー:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <045dbc9c4a3d49a08a3366fc24adee11>:0)
syutugen.Update () (at Assets/syutugen.cs:39)
プログラム:
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
public class syutugen : MonoBehaviour
{
[SerializeField] private GameObject[] enemyPrefabs;
[SerializeField] private Transform LeftTop;
[SerializeField] private Transform RightBottom;
[SerializeField] private int spawnCount = 3;
[SerializeField] private float spawnInterval = 3.0f;
List costomers = new List();
private float minX, maxX, minY, maxY;
private KeyCode destroyKey = KeyCode.Space; // 削除キー
private void Start()
{
// 出現範囲を設定
minX = LeftTop.position.x;
maxX = RightBottom.position.x;
minY = RightBottom.position.y;
maxY = LeftTop.position.y;
// 敵出現処理開始
StartCoroutine(SpawnEnemy());
}
public void AddGameObject(GameObject enemyPrefabs)
{
costomers.Add(enemyPrefabs);
}
void Update()
{
// スペースキーが押されたとき、自身を削除
if (Input.GetKey(destroyKey))
{
Destroy(costomers[0]);
}
for (int i = 1; i < costomers.Count; i++)
{
costomers[i - 1] = costomers[i];
}
}
private IEnumerator SpawnEnemy()
{
for (int i = 0; i < spawnCount; i++)
{
// 毎回乱数を生成
int number = Random.Range(1, 100);
Vector2 position = new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY));
GameObject enemyToSpawn = null;
if (number < 50)
{
enemyToSpawn = enemyPrefabs[0];
}
else if (number < 70)
{
enemyToSpawn = enemyPrefabs[1];
}
else if (number < 90)
{
enemyToSpawn = enemyPrefabs[2];
}
else // number >= 90
{
enemyToSpawn = enemyPrefabs[3];
}
Instantiate(enemyToSpawn, position, Quaternion.identity, transform);
yield return new WaitForSeconds(spawnInterval);
}
}
}