- Home /
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?
Answer by robertbu · Jul 12, 2013 at 10:27 PM
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.)
I did not know that!
You can't make a Inspector variable link to a game object "outside" the prefab
cheers!
So, If I have a prefab that is instanced( and its variables are blank), I know I need to find the Transform and parent / child game Object that I want to set that is in the hierarchy. Also If I'm calling multiple prefabs from an array that are destroyed and called multiple times this would not work? Scene manager is slow. Right? I placed two images to help paint a clearer picture of what I am trying to say. I know the terms I may be using are in the wrong context. Also note that temp parent and carry space both should be assigned carryspace under player.
Your answer
Follow this Question
Related Questions
When adding a script using GetComponent<>(), some prefabs that are assigned don't come up 1 Answer
Does not contain definition 1 Answer
I can modify the GameObject transform using the inspector, how can I modify the mesh as well? 0 Answers
Unity scriptable object inspector, field overlap eachother 0 Answers