Search Unity

Question Start method executed very late

Discussion in 'Scripting' started by FernwehSmith, Jul 13, 2022.

  1. FernwehSmith

    FernwehSmith

    Joined:
    Jan 31, 2022
    Posts:
    36
    Hello all,
    I've got this weird issue where I Instantiate a prefab, get a reference to one of its components, and then call a function on the component. My problem is that the Start method on the component gets executed very late. So even though I'm instantiating the prefab, and then calling the methods on the component, the the methods I'm calling get executed before the Start method does. Obviously this is causing weird behaviour in my script. I've got a work around, but I'm wondering why this is happening in the first place?
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,927
    Start is called before a monobehaviour's first update is called.

    So say you're instantiating a prefab in Update. That prefab is created, you call the methods on it, then the player loop runs around to the next Update, before which the component's Start method is called (this is a super rough way to put it, consult with the timing diagram in the Unity docs).

    In your case you want to use Awake.
     
    Yoreki, Bunny83 and FernwehSmith like this.
  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,927
    Also, follow up post, but fun fact: You can reference prefabs by components that are on the root game object, rather than than the game object itself. You can then Instantiate() them with this reference and it will behave as expected (copy the game object and everything on it/that is a child of it), which returns a reference to the copied component, saving you a GetComponent<T>() call.
     
    Bunny83 and FernwehSmith like this.
  4. FernwehSmith

    FernwehSmith

    Joined:
    Jan 31, 2022
    Posts:
    36
    Ah right I see where I was going wrong! Also thats a great tip thankyou!