Difficulty passing variables to Instantiated Object.

I have been having this problem for a while and I’m only able to make things function using clumsy work arounds. A search for similar issues has not demonstrated the problems I’m having.

I have the following function called from a gameObject.

// Displays StrikeZone
	private void HandleEnemyLocation (StrikeZone strikeZone) {
		GameObject fileDisplay = (GameObject) Instantiate (fileDisplayer, new Vector3 (0, 0, 0), Quaternion.identity);
		fileDisplay.transform.SetParent (hackApp.transform, false);
		ViewerBehavior viewerBehavior = (ViewerBehavior)fileDisplay.GetComponent<ViewerBehavior> ();
		viewerBehavior.SetStrikeZone (strikeZone); 

The Instantiated object, fileDisplay has the following Start() function in the script ViewerBehavior.

// Use this for initialization
	void Start () {
		GameObject blackScreen = transform.Find ("BlackScreen/FileText").gameObject;
		fileNameDisplay = (TextMeshProUGUI) blackScreen.GetComponent<TextMeshProUGUI> ();
		Debug.Log (fileNameDisplay.text);

The Debug.Log does print the appropriate text property, so I know I’m getting a correct reference to my component.

then we call SetStrikeZone (StrikeZone strikeZone) which is located in ViewerBehavior… Set StrikeZone is as follows…

public void SetStrikeZone (StrikeZone sz) {
		this.strikeZone = sz;
		string fileName = BuildFileName (sz.target.formalName);
		Debug.Log (fileName + " created");
		fileNameDisplay.text = fileName;

I continue to get a nullreference exception on the last line “fileNameDisplay.text = fileName;”

It appears fileNameDisplay is null. When I look at the console Debug information, this is what I see…

The Debug.Log is being called in SetStrikeZone BEFORE the Debug.Log is being called in Start() and this explains exactly why fileNameDisplay is null when I call SetStrikeZone() because somehow it’s getting excecuted BEFORE the Start() function which makes no sense to me at all.

I continually have problems setting variables in scripts attached to Instantiated objects because it seems the Object Initialization functions (Start(), OnEnable()) are NOT called before other calls to the script are made.

Is this a bug or am I missing something here? It really seems like instantiating an object and then setting variables on it using a setter function should be a very simple process and yet, I’ve now spent a week trying to do this.

All help appreciated.

I can’t tell for sure but I think this is what is wrong.

There are two functions that get called on a script when the game starts (or a gameobject is made)

void Awake() and
void Start().

Awake is called before Start so if in the Start of one script you ask for a variable that is initialized in the Start of another script there is no easy way to make sure that the Start of the second script is called first. So the variable can be null. If you initialize the variable in Awake() then you can be sure that it will be there when you need it.