- Home /
Duplicate Question
NullReferenceException error in an array of objects
I can't understand why this post was closed for "duplicate question" .-. I don't see the other question, where is it?
Hi, I have a problem with a script.
[...]
void CleanCubes (){
GameObject[] allCube = GameObject.FindGameObjectsWithTag("Cube");
foreach(GameObject current in allCube)
{
foreach(GameObject current2 in allCube)
{
if(current.transform.position == current2.transform.position && current.name != current2.name)
{
toDestroy[arcub] = current2;
arcub = arcub + 1;
Debug.Log (current.name + " & " + current2.name);
}
[...]
The error is
NullReferenceException: Object reference not set to an instance of an object
(wrapper stelemref) object:stelemref (object,intptr,object)
Referring to the line "toDestroy[arcub] = current2;" The objects acctually exist, because if I delete that line, the line "Debug.Log(current.name + " & " + "current2.name")" works as expected. I just can't understand why the compiler can't assign every GameObject in the array toDestroy.
I must use the variable "arcub" for the array, because I don't know how many objects the script will intercept... This is how I instantiated the variables on the top of the class of the script.
public int arcub;
public GameObject[] toDestroy;
I'm sure the error is caused by some stupid mistake I did, but I really can't figure it out... .-. Can someone help me please?