Transform array, index was outside the bounds of the array
So im trying to make this wave system that is configurable, and when i run it all things work well, but when i try to select a random transform from the array spawnpoint, it always says index was outside the bounds of the array, it seems like the Initialize spawn points function is always returning nothing, as i cant seem to access any of the array outside of the function.
//int//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class wavemanager : MonoBehaviour {
public GameObject[] spawnpoints;
public Transform[] spawnpoint;
public GameObject[] enemies;
public static int wavenumber;
public WaveConfig[] waveinfo;
public GameObject Enemy;
int SpawnAmount;
float SpawnRate;
int MaxSpawns;
Vector3 spawnpos;
public bool wavestarted = false;
void Start()
{
initializespawnpoints();
wavenumber = 0;
Debug.Log("Wavestuff initialized");
}
void Update()
{
if (wavestarted == false && enemies.Length == 0)
{
StartNextWave();
}
}
public void FixedUpdate()
{
enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
public Transform[] initializespawnpoints()
{
GameObject[] spawnpoints = GameObject.FindGameObjectsWithTag("Spawnpoint");
Transform[] spawnpoint = new Transform[spawnpoints.Length];
for (int i = 0; i < spawnpoints.Length; i++)
{
spawnpoint[i] = spawnpoints[i].transform;
Debug.Log(spawnpoint[i]);
}
return spawnpoint;
}
public void SpawnRandom()
{
GameObject enemy = Instantiate(Enemy, spawnpoint[UnityEngine.Random.Range(0, spawnpoint.Length)].position, Quaternion.identity);
float Health = enemy.GetComponent<EnemyMovement>().health;
Health = Health * wavenumber;
enemy.GetComponent<EnemyMovement>().health = Health;
float Speed = enemy.GetComponent<EnemyMovement>().speed;
Speed = Speed * 3 + wavenumber * 0.05f;
enemy.GetComponent<EnemyMovement>().speed = Speed;
}
public void StartNextWave()
{
wavestarted = true;
wavenumber++;
FindObjectOfType<SceenDisplay>().wavecounter(wavenumber);
Debug.Log("Startnextwave");
newwaveinfo(wavenumber.ToString());
StartCoroutine(EnemySpawning());
}
public void newwaveinfo(string name)
{
WaveConfig s = Array.Find(waveinfo, waveinfo => waveinfo.name == name);
SpawnAmount = s.spawnamount;
SpawnRate = s.spawnrate;
MaxSpawns = s.maxspawns;
}
public IEnumerator EnemySpawning()
{
while (SpawnAmount > 0)
{
if (SpawnAmount > 0 && MaxSpawns > enemies.Length)
{
SpawnAmount--;
yield return new WaitForSeconds(SpawnRate);
SpawnRandom();
}
else
{
yield return new WaitForSeconds(5);
}
}
if (SpawnAmount == 0)
{
wavestarted = false;
}
}
}
Comment