- Home /
Null reference when editing an array in a for loop
Hey guys, I've looked around a bit and couldn't find a great answer for this one so here goes: I'm trying to edit the positions of an array of gameobjects, but keep getting a null object reference. I think I'm just declaring/ editing the array incorrectly. Anyways, here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawner: MonoBehaviour {
public GameObject enemyPrefab;
//time to wait before spawning starts
public float spawnDelay;
//time between each spawns
public float spawnTime;
public GameObject [] spawnLocations;
private int spawnLocationIndex;
public int maxDistance;
public Transform target;
public Transform spawnerTrans;
private int enemyCount = 0;
void Awake() {
spawnerTrans = transform;
}
// Use this for initialization
void Start () {
GameObject player = GameObject.FindGameObjectWithTag ("Player");
target = player.transform;
maxDistance = 5;
StartCoroutine (SpawnTimeDelay());
//need to set up a randomized array of spawn locations for enemies to spawn from
//TODO: Make it so that the spawn locations can't be too close together
//TODO 2: Make it so that there can only be a certain number of dudes out at a time
int range = (Random.Range(2,8));
Debug.Log ("range is " + range);
//spawnLocations = new GameObject[range];
/*
*********************
Here's the block that screws everything up
*********************
*/
for(int i = 0; i < range; i++){
if (spawnLocations [i] == null){
Debug.Log (i + " is null.");
}
GameObject temp = new GameObject();
temp.transform.position = new Vector3 (Random.Range(9.5f,11f), Random.Range(-6f,0.5f), 0);
spawnLocations[i].transform.position = temp.transform.position;
}
}
IEnumerator SpawnTimeDelay () {
while (true) {
if (Vector2.Distance (target.position, spawnerTrans.position) < maxDistance) {
Instantiate (enemyPrefab, transform.position, Quaternion.identity);
enemyCount++;
yield return new WaitForSeconds (spawnTime);
}
if (Vector2.Distance (target.position, spawnerTrans.position) > maxDistance)
{
yield return null;
}
}
}
}
Where do you fill/initialize the array in the first place ? If you fill it in the inspector, try replace the line :
int range = (Random.Range(2, 8));
with
int range = (Random.Range(2, spawnLocations.Length));
This will ensure the random range never exceed the array capacity. (that is, assu$$anonymous$$g your array has at least 2 entries)
what I'm trying to do is declare a global array, then fill it in start. Is that something you can do in c#?
you are never assigning anything to the array. you shouldn't need the temp variable. just assign the new gameobject directly to the array :
spawnLocations [i] = new GameObject();
Answer by Lazdude17 · Apr 07, 2018 at 06:57 PM
Uncomment your //spawnLocations = new GameObject[range];