Finding specific object in array

I am trying to come up with a way of specifying which single object within an array I want to access.

By clicking on a gameObject, it sets a public bool of isSelected to true (and is reset as something else gets isSelected = true). As a gameObject is instantiated, it is added to an array list of units.

I am trying to work out how to say GameObject objectIWant = (objectInArray.isSelected = true);

After trying different solutions such as -

GameObject g = (GameObject)selectionMovement.isSelected;

I am a bit stuck on how to look for whichever object currently has the bool. The access methods given are GetType, which I think doesn’t apply. GetComponent doesn’t appear to be valid. GetValue, appears to be where in the list it might be.

How can I go about looking for the gameObject which has isSelected as true?

Thank you.

where is the bool that is setted to true ? is der a spereate array for each gameobject, or do the gameobjects have scripts on itself ?

The bool is on a separate script on each of the gameObjects.

You iterate through the array, and pick the first element that’s selected. All you need is a normal for-loop.

Though, if there’s only one unit that can be selected at a time, it’s probably easier to register the selected unit somewhere, instead of setting a bool that you look for:

public class Unit : MonoBehaviour {
    
    public static Unit selected { get; private set; }
    
    void OnClicked() {
        selected = this;
    }
}

And when you need it:

void DoSomethingToSelecedUnit() {
    Unit selected = Unit.selected;
    if(selected != null)
        DoSomethingTo(selected);
}

You could also register it on some object, or whatever. The point is that unless the Unit itself needs to know if it’s selected or not, it’s probably better to not have it carry that information around, and then go looking for it when you need it.