How to deal with a missing reference when an object referred each frame from an array is destroyed along the way?

##Context:

In the Start method, I instantiate a flock of flying bugs and store them in a list called “agents”.

In the Update method, I iterate on each agent in the list to: 1) store their transforms, 2) get a list of its neighbors’ transforms and 3) calculate the movement of the flock based on the agent and its neighbors.

To check for neighbors, I used a method called GetNearbyObject to which I passed each agent. This method looks for colliders in a certain radius and store them in an array of colliders. Then, it iterate on each collider in the array to get their transforms. It returns a list of transforms that is needed to calculate the movement of the flock for each frame.

##Problem:

My problem is that my flying bugs can be destroyed anytime when the player shoots at them. When a bug is killed, I get a “Missing Reference” error saying that one of my bug has been destroyed while the code still tries to access it.

It seems that since my bugs’ colliders are stored in the array of colliders each frame, I can’t manage to tell my code to ignore the newly destroyed bug’s collider. I tried to add some if statements to check if a bug agent returns null and then remove it from both lists, but it doesn’t remove the Missing Reference. I’ve also tried to disable the bugs’ colliders when they return null after being destroyed. Doesn’t work either.

If someone could help me get rid of this error, that would help me a lot in my learning curve of Unity and C#. Here is the concerned block of code:

void Update()
{
    foreach (FlockAgent agent in agents)
    {
        if (agent == null)
        {
            agents.Remove(agent);
        }

        List<Transform> context = GetNearbyObjects(agent);
        
        if (agent == null)
        {
            context.Remove(agent.transform);
        }

        Vector3 move = behavior.CalculateMove(agent, context, this);

        move *= driveFactor;
        if (move.sqrMagnitude > squareMaxSpeed)
        {
            move = move.normalized * maxSpeed;
        }
        agent.Move(move);
    }
}

List<Transform> GetNearbyObjects(FlockAgent agent)
{
    
    List<Transform> context = new List<Transform>();

    Collider[] contextColliders = Physics.OverlapSphere(agent.transform.position, neighborRadius);

    foreach (Collider c in contextColliders)
    {
        if (c == null)
        {
            context.Remove(c.transform);
        }
        else if (c != agent.AgentCollider)
        {
            context.Add(c.transform);
        }
    }
    return context;
}

Need help with the same problem, gonna watch this thread

I think youve basically got this problem Remove elements from a list while iterating over it in C# | Techie Delight