Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Creating new class asynchronous?

Discussion in 'Scripting' started by kortenoever, Feb 19, 2018.

  1. kortenoever

    kortenoever

    Joined:
    Jun 12, 2013
    Posts:
    11
    Hello,

    Does anyone know why this doesn't work.
    Code (CSharp):
    1. public class buildingTypes {
    2.         public GameObject[] bottomSym;
    3.    }
    4.  
    5.    public buildingTypes[] buildingType;
    6.  
    7.    IEnumerator determineBuildingTypeAmount (int levelInt){
    8.  
    9.         buildingType = new buildingTypes[3];
    10.         buildingType [0].bottomSym = new GameObject[3];   ---> NullReferenceException
    11.         yield return new  WaitForEndOfFrame ();
    12.  
    13.     }

    But this works (most of the time):
    Code (CSharp):
    1. public class buildingTypes {
    2.         public GameObject[] bottomSym;
    3.    }
    4.  
    5.    public buildingTypes[] buildingType;
    6.  
    7.    IEnumerator determineBuildingTypeAmount (int levelInt){
    8.  
    9.         buildingType = new buildingTypes[3];
    10.         yield return new  WaitForEndOfFrame (); < -- this line added
    11.         buildingType [0].bottomSym = new GameObject[3];
    12.         yield return new  WaitForEndOfFrame ();
    13.  
    14.     }

    Is creating a new class asynchronous?
    How do i make sure when to call buildingType [0].bottomSym = new GameObject[3]; ?

    Thanks!
     
  2. Rotary-Heart

    Rotary-Heart

    Joined:
    Dec 18, 2012
    Posts:
    813
    When you initialize your array you are not adding any instance. So after line 9 you end up with an array of 3 null references. You will need to initialize them individually. Either with a loop or manually.

    Code (CSharp):
    1. buildingType = new buildingTypes[3];
    2. buildingType [0] = new buildingType();
    3. ...
    As for why it works most of the time. My bet is that if this is drawn on the editor, Unity will add a default value so you will not end up with a null reference, but you will have to "wait" until unity adds it.
     
    kortenoever likes this.
  3. kortenoever

    kortenoever

    Joined:
    Jun 12, 2013
    Posts:
    11
    Thanks a lot!
    Learned something new. It works