# Unity prefab script "GameObjects" can't be ones on the scene?

Currently, I have an object on the scene, and one in prefab. I want the prefab's script to reference to the object on the scene through the

public GameObject obj;


code. However, when I tried to add the object in the editor, I cant seem to be able to select any objects from the scene, only ones in prefabs.

I am quite new at unity, so am I missing something really basic here?

Thanks for any help!

## 3 Answers

If you have the gameobject with the code attached selected, you can drag the gameobject in the scene using the hierarchy to the inspector.

Confusing I know, here is a picture:

EDIT: Strike that, this is more accurate:

With unity, you can not reference things in the hierarchy from a prefab. You need to somehow add it at runtime. A cheap way to do this is to store 'the gameobject in the scene' in a static variable. For instance something like:

public static GameObject thingonstage;
void Start(){
thingonstage = this.gameobject;
}


Then later, you reference the static global variable to get at it.

• So to assign the variable, I should make a script for the object that I want to assign, then reference the global variable to set it? Thanks EDIT: I did that, but it didn't seem to work... Jan 22 '15 at 7:58
• Nevermind, it works! Just that I used a object I dragged out of the prefab, instead of the ones that spawns ingame. Thanks! Jan 22 '15 at 8:13
• Np, glad to hear you got it to work! Jan 22 '15 at 8:14
• Hint: The member does not need to be static nor a GameObject. Any public MonoBehaviour member can be set this way. Jun 12 '15 at 9:10

Prefabs are supposed to be reusable between different scenes. They can not reference a game object in the scene hierarchy, because that object would be unavailable if the prefab is used in a different scene. That's why prefabs can only reference assets, other prefabs or parts of themselves (like their children).

What you can do instead:

• Have your Start method find the object to interact with in the scene. There are several ways you can do that. You can use GameObject.Find to find it by name (can be slow if you have a lot of objects in the scene), you can assign an unique tag to the object and then use GameObject.FindWithTag or you can use the singleton pattern in a script on the referenced object.
• Assign the object to interact with when you instantiate the prefab. If you spawn the prefab from a script, then that script will need to have a reference to the object. If you create a prefab instance in the Unity editor, you will have to assign that reference manually.

Drag & drop the appropriate gameobject from your scene hierarchy to the property you want to set.