- Home /
foreach fills array with
I'm receiving a NullReferenceException from a foreach loop that is locating a series of sprites based on their tag. The loop is finding all of the present objects and incrementing the array appropriately. But it is only transferring the last of the found objects into the array. All the other sectors are being filled with null.
foreach(OTSprite go in temp){
if(go.gameObject.tag=="building"){
buildings=new OTSprite[i+1];
buildingOrigin=new Vector2[i+1];
buildings[i]=go;
buildingOrigin[i]=buildings[i].position;
buildings[i].position=beneathScreen;
i++;
}
}
You need to format this code properly. Highlight all your code and press the '101010' button in the formatting bar in your question box.
I have rewritten this post 4 times and it refuses to format correctly. Thanks, Unity!
Answer by Berenger · Mar 07, 2012 at 08:47 PM
You are re-affecting buildings and buildingOrigin at each loop, so at the end you only have the last iteration, with the information at the index temp.Length-1. Declare and initialize those two arrays before the loop.
Is there a way to change the size of the array dynamically? This code runs in different scenes that do not always have the same values.
If you don't want to use lists, I added a script in the wiki to use built-in array sort of like lists, here. There isn't a resize function though, because Array class already have one.
Actually in that case, the size will be temp.Length, so just declare buildings = new OTSprite[temp.Length]. If the size don't change after that creation, don't $$anonymous$$d the beggining of that comment.
Your answer
Follow this Question
Related Questions
FindWithTag in certain range 2 Answers
C# - foreach problem 3 Answers
Arraylist to GameObject[] array issue. 1 Answer
Accessing a prefab after instantiating results as null 1 Answer
Unable to delete object from a list using foreach loop 1 Answer