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 *=  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

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:

[Unity - Manual: Tags][1]

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 _= gos*.GetComponent<Badguys>();*_

}
Note that using Linq can simplify this process into a single line of code. Here is a short tutorial:
[unitygems.com - unitygems Resources and Information.][2]
[1]: http://
_*[2]: unitygems.com

It’s just working as a charm
Thanks a lot