How to handle NullReferenceExceptions from destroyed objects?

Hi there,

I have a list of GameObjects over which I want to do some operations. I’ve saved the list into a private variable as such:

Creatures = GameObject.FindGameObjectsWithTag("Creature") ;

Elsewhere in my code, I’m trying to store information about the creatures into a list.

private List<float> GetVelocities(GameObject[] creatureList) {
        List<float> temp = new List<float>();
        foreach(GameObject creature in creatureList) {
            temp.Add(creature.GetComponent<CreatureAttributes>().Velocity);
        }

        return temp;
    }

The problem is that if a creature is destroyed in between, a NullReferenceException is made.

This can be solved by putting an if statement to check if the creature is not null before trying to access it’s field, but this seems somewhat inelegant.

Is there a better solution for checking if the object is not null?

Thanks.

I would create a list of CreatureAttributes and have the objects with that class add and remove themselves from that list. Then iterate through that list rather than spending extra cpu time on GetComponent calls.

Thanks for the response! I’m not quite sure how to achieve what you are suggesting. I’m thinking of create a static list elsewhere which the CreatureAttributes could attach themselves in the Start function. Is there a similar function that defines a method for when the object is destroyed?

OnDestroy or OnDisable are the unity method calls.