How to find an ACTIVE gameobject in array C#

Hello!

I’m using a “Gameobject Pool” I got an array of 100 gameobjects that I instantiate on start so when I click 1 of the 100 gameobjects is activated.

I have a Cannon that needs a target randomly but it needs to be active

So I made a script to seek in the array for a random gameobject and is working fine BUT it looks for deactive gameobjects too, i just want it to seek active objects and choose one!

This is my script:

GameObject[] ducks;
GameObject Target;
int index;


void SeekTarget(){

	while (!Target.activeInHierarchy) {
	     index = Random.Range (0, (ducks.Length - 1));
	     Target = ducks[index];
				
      }
	
}

So What I’m Trying to do here is a while loop that continues to check for a random object in the array until “Target” is active. The problem is that I get this error on this line " while (!Target.activeInHierarchy) {"
NullReferenceException: Object reference not set to an instance of an object

How do i do it? or theres another better way?

If you aren’t calling SeekTarget every update then this should work fine for you.

/// <summary>
/// Generates a list of active ducks and randomly sets one of them as a target.
/// </summary>
void SeekTarget()
{
	List<GameObject> activeDucks = new List<GameObject>();
	// Cycles through all of the ducks.
	foreach (GameObject duck in ducks)
	{
		// Checks if the current duck is active, if it is then it adds it to a temporary list.
		if (duck.activeInHierarchy)
		{
			activeDucks.Add(duck);
		}
	}

	// Generate a number between 0 and the list of active ducks last index.
	index = Random.Range(0, activeDucks.Count - 1);

	// Grab the duck at the specified index in the list of active ducks.
	Target = activeDucks[index];
}