Search Unity

Unit scripts calling Start function before other scripts

Discussion in 'Scripting' started by zehuntar21, Aug 9, 2021.

  1. zehuntar21

    zehuntar21

    Joined:
    Oct 1, 2019
    Posts:
    6
    Hey,

    So im working on a unit movement scene, where units move on a hextile map. It was all working fine, until I duplicated some units. Now the duplicated units are not working properly, because they are calling their start function before my HexTileMapGenerator calls its start function. The other units work fine, only the freshly duplicated units are calling their start function before. I did some print statements and indeed, the units that work correctly are calling their start function after the HexTileMapGenerator calls his.

    Whats a suitable solution to this problem? Its the first time I encounter this problem.

    Thanks in advance
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,459
    There's both Start and Awake with Awake being guaranteed to be called before all Starts. The actual order of any of these calls though is controlled by the script execution order so lots of options there.
     
    Last edited: Aug 9, 2021
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    I think you have a typo? Awake is called before all Starts?
     
    MelvMay and Lekret like this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,695
    Indeed. I like to use a lot of additively-loaded scenes, so I tend to code my individual item controllers (including the player controller) so that they are happy to wait around if other stuff isn't ready yet.

    You can make Start() into a coroutine, which is a super-easy way to get this kind of lazy-sloppy startup that is extremely tolerant of late loading and uneven loading.

    Code (csharp):
    1. // typical base framework for all entities
    2.     bool ready;
    3.  
    4.     IEnumerator Start ()
    5.     {
    6.         // don't proceed until the hex tilemap is ready
    7.         while( MyHexTileMap.Instance == null)
    8.         {
    9.             yield return null;
    10.         }
    11.  
    12.         transform.position = MyHexTileMap.Instance.GetSpawnPoint();
    13.  
    14.         ready = true;
    15.     }
    16.    
    17.     void Update ()
    18.     {
    19.         if (!ready) return;
    20.  
    21.         // everything else here...
    22.     }
    23.     void FixedUpdate ()
    24.     {
    25.         if (!ready) return;
    26.  
    27.         // everything else here...
    28.     }
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,459
    I did indeed, I'll correct that! Rushed post!
     
    Kurt-Dekker likes this.