- Home /
Object reference not set to an instance of an object
using UnityEngine;
using System.Collections;
public class enemySpawner : MonoBehaviour {
private int c;
private Vector3[] spawnPoints;
void Awake() {
BoxCollider b = gameObject.collider as BoxCollider;
for (int x = 0; x <= b.size.x; x++) {
for (int z = 0; z <= b.size.z; z++) {
spawnPoints[c] = new Vector3(x, 0, z); //this is where I get the error
c++;
}
}
print(spawnPoints);
}
}
And the full error:
NullReferenceException: Object reference not set to an instance of an object
enemySpawner.Awake () (at Assets/Scripts/enemySpawner.cs:14)
What am I missing? As far as I can tell, the code is correct. I guess C# is just extremely picky. I'm sure this is a very easy fix, thanks in advance.
Answer by Dave-Carlile · Feb 09, 2013 at 04:12 AM
You've declared a spawnPoints
array, but you haven't allocated memory for it.
Inside your Awake
function, you need to allocate the array...
spawnPoints = new Vector3[x];
Where x
is the number of elements you want to allocate.
What if I want it to be dynamic though? I don't want to have to set the size, and I would rather not have to loop through twice just to be able to get the size.
Your answer
Follow this Question
Related Questions
GUISttyle NullReferenceException error. what am I missing ? 1 Answer
Referencing a variable to a prefab from another script that is applied to multiple game objects 0 Answers
Getting ArgumentOutOfRangeException on array c# 1 Answer
How to properly create a 2 dimensional array of an object. [C#] 1 Answer
Tagged objects not returning value 0 Answers