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.

Is there some sort of delay in Instantiate?

Discussion in 'Scripting' started by KeTo166, Jan 12, 2018.

  1. KeTo166

    KeTo166

    Joined:
    Jan 3, 2018
    Posts:
    2
    Hi, does anybody else get null reference errors for things that should already be instantiated? I've run into this twice now.

    Code (CSharp):
    1. //\Scripts\Game_Scene\GameManager
    2.  
    3. void Start () {
    4.         ...
    5.        
    6.         Instantiate(boardManager);
    7.        
    8.         ...
    9.  
    10.         //startPosition = new Vector3((BoardManager.instance.maxCols / 2), (BoardManager.instance.maxRows / 2), 0f);
    11.         Invoke("Test", 0f);
    12.        
    13.  
    14.  
    15.     }
    16.  
    17.     private void Test()
    18.     {
    19.         startPosition = new Vector3((BoardManager.instance.maxCols / 2), (BoardManager.instance.maxRows / 2), 0f);
    20.     }
    21.    
    22.  
    So game manager starts up on a scene, and it instantiates one prefab BoardManager gameobject and its singleton script object. It has two public variables, maxRows and maxCols that I want to use to setup a variable in this game manager script, so I'd assume those maxRows and maxCols should be available as soon as I it finishes instantiating BoardManager, but instead, I get a null reference error from anything in BoardManager.

    Testing it, if I invoke a method "Test" with a delay of 0f seconds, it picks up BoardManager vars no problem. Is there a delay or some kind of method the compiler takes that would cause this issue with instantiate? From what I could find, it looks like instantiate is supposed to be straightforward, ie no delay or short cutting around code. Any help? Or should I always just have some sort of second "Start" method that is called when everything has finished loading?

    So, with the sample code above, if I uncomment startPosition's assignment before the invoke, I get an null reference exception thrown at line 10. In boardmanager, I don't use any invoke, coroutines, or anything I think is supposed to have a delay to it. My full code can be found:
    https://github.com/keto166/Tetris_Like_Exercise

    Thanks!
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I had to open your other code to verify the issue.
    It's because you assign the instance variable in Start(), which is run after Awake(), which is run before you call your position code :)
     
    KeTo166 likes this.
  3. KeTo166

    KeTo166

    Joined:
    Jan 3, 2018
    Posts:
    2
    Ahhh, that fixes it. Thank you!
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    No problem :) you're welcome.