- Home /
Fill array with script c sharp
hi guys i have an array that i want to fill up script here is it :
public badguys[] Badguys ;
Void foo(){
for(int i=0; i<30; i++)
{
badguys[i] = GameObject.Find("badguy").GetComponent<Badguys>();
}
}
30 is just a random number, i have around 10, it's just to be sure but i' like my array to be the good the extact number of badguys in the scene. the badguy are Empty in the hierarchy witch i've attach Badguys to them; but when i launch the game unity return me
NullReferenceException: Object reference not set to an instance of an object
do i need to instanciate???? dont know really how to do
thanks guys
Answer by robertbu · Apr 16, 2014 at 05:04 PM
The way you are going about it here will not work. GameObject.Find() returns the first one found, so you will not get any others. The usual solution is to tag all the game object you are interested in with the same tag:
http://docs.unity3d.com/Documentation/Components/Tags.html
Then you can use GameObject.FindGameObjectsWithTag() to get an array of game objects with that tag. Then you can cycle through and create an array of the component you are looking for:
GameObject[] gos = GameObject.FindGameObjecsWithTag("gadguy");
badguys = new Badguys[gos.Length];
for (int i = 0; i < gos.Length; i++) {
badguys[i] = gos[i].GetComponent<Badguys>();
}
Note that using Linq can simplify this process into a single line of code. Here is a short tutorial: