- Home /
Duplicate Question - actually a duplicate of a duplicate
NullReferenceException error in an array of objects
I don't understand why they closed my question a few hours ago, anyway, I will try to repost it, and if there is any problem, please be more specific so that I could understand why my question was closed. 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?
was there a line number in the error message?
(foolishly) assu$$anonymous$$g that your error is from toDestroy[arcub] = current2;
- it's because you haven't initialized toDestroy[]
properly.
if you're using an array then it needs to be initialized like
public GameObject[] toDestroy = new GameObject[xxx];
where xxx is the size.
if you don't know the size (quite likely) then consider using a List
ins$$anonymous$$d. adding to it is a case of listName.Add(item);
and you can still index the members like you would with an array. don't forget to add the appropriate using statement to your class.
I closed your question because there are many questions and answers about NullReferenceException problems. Please read those, and, if you are unable to resolve your problem, explain in detail what you've done to solve this, and what you need help with. I'll now close this one. Answers isn't a "what's wrong with my code" site.
Follow this Question
Related Questions
NullReferenceException error in an array of objects 0 Answers
C# - instance is not set to an instance of an object 2 Answers
Object reference not set to an instance of an object 1 Answer
error CS0118: `New_Career.Fame' is a `field' but a `type' was expected 1 Answer
NullReference when accessing GameObject in array (C#) 1 Answer