0
\$\begingroup\$

Okay, I have a prefab with a script. It has the public field gameobject, and I see that in the inspector. When I try to drag an object from the scene into that slot, I'm simply unable to. No error or anything, just acts like it's any other part of the screen.

Is there a type mismatch here? How do I drag something from the hierarchy?

\$\endgroup\$
1
  • 2
    \$\begingroup\$ A prefab exists in a kind of "game-global" scope, while an object in a particular scene exists, well, only in that scene. So you can't drag a scene object into a prefab's inspector - the scene object won't exist at all times that the prefab does. You can drag a scene object into the inspector of another object in the same scene, or a prefab into a scene object's inspector, or a prefab into a prefab's inspector. But a prefab referencing an object that exists only in a specific scene just doesn't make sense from Unity's point of view. \$\endgroup\$
    – DMGregory
    Feb 3, 2015 at 1:31

2 Answers 2

0
\$\begingroup\$

I think the problem is that the prefab can not see instantiated objects that are already in the scene. A way to think about this is: What would your game do if it instantiated the prefab in a scene without that other asset, even though you linked it in the prefab? "Well, I'm not going to do that though" is not a good excuse to the Unity Editor, for what reason I don't know.

My preferred method to get around this is to add a reference to the object at run-time. Depending on what you are working on, it might be as simple as:

//On the Gameobject in the scene
public void Start(){//you can use start, awake, or other event as needed
    OtherComponentClassOfPrefab.staticSetupMethod(this.gameobject);//using a static method to pass this reference to other class.
}


//On the Prefab that uses the other object in the scene
public static staticSetupMethod(GameObject go){
    go.Stuff();//do stuff to go, or store it for later use.
}

Again, depending on your setup, if a singleton works for you then you can pass the reference to the instantiated prefab directly through that. And if not, a variation of the above will go pretty far if you are creative enough with it. Hope that helps!

\$\endgroup\$
0
\$\begingroup\$

make a prefab of the object you will use as yourObject then drag it in the script's public field from the "project" tab rather than the scene

enter image description here

\$\endgroup\$
2
  • \$\begingroup\$ I am using the proper casing: public GameObject mousemanager; I don't want to use a workaround for the rest of the time I make games, is there a solution? \$\endgroup\$
    – Daniel Bak
    Feb 3, 2015 at 0:58
  • \$\begingroup\$ yes drag your object to the Project side to prefab it. Click on your object with the script to see the field Then you can drag the prefabed version to the gameobject field \$\endgroup\$ Feb 3, 2015 at 1:02

Not the answer you're looking for? Browse other questions tagged .