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. Dismiss Notice

Get Components in children returns error

Discussion in 'Scripting' started by TheCelt, Apr 22, 2016.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    718
    Hello

    I have a script which gets components in children on Start but it seems to give an error. I definately have a child GameObject which has the relevant component attatched.

    The game object is also set inactive at the start but i put true in the second parameter so it should be retrieving it... this is my code:

    Code (CSharp):
    1. private InteractHandler[] interactions;
    2.  
    3. void Start(){
    4.      interactions = GetComponentsInChildren<InteractHandler>(true);
    5.      print(interactions.Length); // returns 1
    6. }
    I then iterate through the array like this but i get an error on my for loop:


    Code (CSharp):
    1. void ToggleInteractions(bool isEmpty){
    2.     for(int i = 0 ; i < interactions.Length; i++){ //ERROR
    3.         //DO stuff
    4.     }
    5. }
    The error is:
    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    What is the reason this happens?
     
  2. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Unless I'm missing something obvious that should not happen unless the code executes in reverse order, that is Toggle Interactions before Start, assuming no other code interferes. Are you sure it's executing in the order you describe, because the error means interactions has not been assigned yet or has explicitly been set to null.
     
    Not_Sure likes this.
  3. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    718
    The toggle function calls from another script when collider sets off the ontriggerenter function. The character starts in the collider so it fires on trigger enter when the game starts, could this be why?
     
  4. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Easiest way to find out is to just Debug.Log("MethodName", this) in those methods, and they will log to the console in the order they're executed.
    If the order is indeed wrong because of this, one way to fix it could be to move the array initialization to Awake instead of start, or just do a lazy initialization whenever you access it the first time.