Will an instantiated object ever exist before the next line of code in the object that creates it?

Lets say I have code like this

  GameObject instantiatedEnemyObject = Instantiate(gameObject) as GameObject;
  BadGuyScript script = instantiatedEnemyObject.GetComponent<BadGuyScript>();
  script.isThisInstantiated = true;

My question is - will there ever be a situation where the instantiatedEnemyObject will ever begin to run the code in BadGuyScript before i am able to tell it that it is instantiated?

(I know there are ways to tell dynamically if an object is instantiated but I’m just asking for other situations.)

Core parts of Unity like that are single-threaded. The object will be completely instantiated and integrated before the method returns.

This is true and yet… I think it answers OP’s question, but OP is asking it from the opposite side:

OP asked:

… so I think the answer to OP is actually that YES, when you call Instantiate, other code can run (code in Awake() and OnEnable() for example) before the reference to the newly-instantiated thing comes back.

3 Likes

I think this is real. I was able to have some code for my enemy to instantiate itself, but I was telling it to not do that by accessing its script and changing the isThisInstantiated boolean. They then instantiaed themselves in a daisy-chain and my unity ran out of memory and crashed in about a minute.

Put that sorta code in Start().

Here’s why:

Anything in Awake / OnEnable runs BEFORE the Instantiate returns to you, as I said above.