Assign object in hierarchy as public variable in prefab

I have an object that runs all of my game logic called GameController.

I want each instantiation of a certain prefab to be able to access that gameController.

In the script of the prefab, I have:

public var variableGameController:GameObject;  

Here’s the problem, though.

Experimentation has shown that if you drag the GameController object to the variableGameController in the inspector,

that information is not propagated in to instances of the prefab. In the prefab instances, the field just remains blank.

Why? What to do?

A prefab is a plan for a game object, not a game object. You can drag and drop variables between game object internally, but you cannot and drop externally. That is, you can create internal linkages between the scripts on the various parents and children of the prefab, but since since the prefab/plan does not know about it environment, you cannot make direct references beyond the prefab to other game objects.

There are a variety of solutions. The most common is to use GameObject.Find() or GameObject.FindWithTag() to find the the external link. This is usually done in the Start() function of any script in the prefab that needs to reference another gameobject/script. Another solution is to use a Singleton to provide global access to data.


The very easiest way… assuming you have only “one” of the thing in question … just use FindObjectOfType

/// here we are in a prefab...
public SceneManager myBoss; /// won't work!
private SceneManager myBoss; /// so do this...
public void Awake()
	{
	myBoss = Object.FindObjectOfType<SceneManager>();
	}

(Be aware this is quite slow; do not do many of these at game time or in a loop at game ime. It’s absolutely fine to do this at startup or scene startup.)