Variables getting reset weirdly after Instantiation... confused...

I am instantiating game objects like this

GameObject go = Instantiate(Resources.Load("Prefabs/AIBlob")) as GameObject;
		
		BlobController aiBlob = go.GetComponent("BlobController") as BlobController;
		aiBlob.init(size);
		
		Debug.Log("created blob, "+aiBlob.transform.position+"  energy="+aiBlob.physicalState.energy);

This outputs that energy has been set to a value like 1.

Then, when Update() is called on this game object, physicalState.energy is 0. Why is that happening? Why are these variables getting reset? I noticed that Start() also gets called AFTER init() here… and when Start() gets called physicalState.energy is 0. Why???

Anyone know what I’m talking about?

Thanks for your help!

EDIT I also have code that should not be run unless objectA.getInstanceID() == objectB.getInstanceID()
and then in the code that should not get run if those two IDs are the same, I can output them, and they are always both the same negative number. are getInstanceID() supposed to be 0? Is my Unity broken? Wtf???

It appears you are using c# , but your GetComponent is wrong, should be:
go.GetComponent();
and you shouldn’t need to cast it that way, and don’t use quotes. It’s a type.

I don’t think there’s anything wrong with the way he uses GetComponent.
IIRC you can have it either way,

T component = GetComponent();
T component = GetComponent(“T”) as T;

@OP:
Can you show us what happens in init and start? We really don’t know how/when the variables are getting set.

Start() doesn’t get called until before the first frame update. (See Execution Order of Event Functions) It doesn’t get called right away. Awake() gets called immediately after a prefab is instantiated. You could:

  • Use Awake(),
  • Rewrite your Start() and/or init() functions to play nicely with each other, or
  • Run init() in a coroutine that waits a frame before doing its work.