Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to handle NullReferenceExceptions from destroyed objects?

Discussion in 'Scripting' started by unity_FhaTgXjem9_ZZw, Jun 3, 2020.

  1. unity_FhaTgXjem9_ZZw

    unity_FhaTgXjem9_ZZw

    Joined:
    Oct 10, 2018
    Posts:
    8
    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:

    Code (CSharp):
    1. Creatures = GameObject.FindGameObjectsWithTag("Creature") ;
    Elsewhere in my code, I'm trying to store information about the creatures into a list.

    Code (CSharp):
    1. private List<float> GetVelocities(GameObject[] creatureList) {
    2.         List<float> temp = new List<float>();
    3.         foreach(GameObject creature in creatureList) {
    4.             temp.Add(creature.GetComponent<CreatureAttributes>().Velocity);
    5.         }
    6.  
    7.         return temp;
    8.     }
    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.
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    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.
     
  3. unity_FhaTgXjem9_ZZw

    unity_FhaTgXjem9_ZZw

    Joined:
    Oct 10, 2018
    Posts:
    8
    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?
     
  4. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    OnDestroy or OnDisable are the unity method calls.