"Losing" variables in GameObject components

Hi,

I’m having a problem where I “lose” variables during object setup. I’m going nuts here, I can’t understand what happens. Here’s what I do:

environment.cs

class Environment () {
	
	public GameObject go; // set in Inspector, inactive in the beginning
	
	DataController dc = go.GetComponent<DataController>();
	dc.Init("shipName");
	
	go.SetActive(true);
	}

“Ship” GameObject has a DataController and a AppearanceController

DataController

class DataController () {

	string shipName;
	Hashtable dataShip;

	void Init (string shipName) {
		Debug.Log("INITING DataController");
		
		dataShip = someWhereElse.loadDatabase(shipName);
		
		shipName = dataShip[someTestVariable];
		
		Debug.Log(shipName); // prints: "shipName"
		}
}

AppearanceController

class AppearanceController () {
	void Awake () {
		Debug.Log("AWAKE in AppearanceController");
		
		dc = this.GetComponent<DataController>();
		Debug.Log(dc.shipName); // prints: null
	}
}

How come that between the Init of the DataController and the Awake of the AppearanceController the variable “shipName” get “lost” basically?!

Notice that this is quite random. When I place a second Ship GameObject in the scene (that has some other components additionally, which don’t do anything), it works.

Line 7 in DataController declares a variable named shipName in scope of the Init method only so as soon as the method returns that variable is “lost”.

No no don’t worry, string shipName is declared right under the class name and above the Init, along with a bunch of other stuff. I just left that out for clarity. Will edit that in.

I’m beginning to suspect it has something to do with the fact that the ship is inactive at the beginning, and it SetActive(true) later. When exactly is a Awake function called if the object is inactive at the beginning?

If the GameObject starts as inactive then Awake is called as soon as it becomes active. If you are creating the GameObject via Instantiate() then Awake is called immediately.