- Home /
Public script references in the Inspector
What does it mean exactly when a public Inspector variable is of a custom class, like this:
public MyClassName myClass;
I know that a class inheriting from MonoBehaviour is instantiated when dragged as a component onto a GameObject. I believe most MonoBehaviour scripts are meant to be used in this fashion. But what happens when I drag the script onto an Inspector field? Is it instantiated (probably not)? Some notable use cases would be very much welcome. Thanks.
Answer by pako · Feb 10, 2018 at 01:20 PM
But what happens when I drag the script onto an Inspector field?
You can't (try and see). Unity won't let you drag a script from you Assets folder in an Inspector field, because if I understand your question well, this is what you had in mind. And this of course, is because an instance of this script hasn't been created yet.
And when you drag a GameObject with a particular script on it, on to an Inspector field, the field contents display "GameObjectName. (MonoBehaviourName)", indicating the instance.
Answer by hexagonius · Feb 10, 2018 at 10:16 AM
it's basically the same as if you did int i = 5
. it's a way of doing the assignment via inspector. What Unity does is literally writing a list of everything existing in a scene. when the scene content is created the underlying system brings those things together that have been linked like that in the inspector so you don't have to do that in code. its not instantiating anything, just referencing.
But it is referencing a class, not an instance, right? How would this be used (except for allow a prefab that contains that script to be dropped onto the field)?
As pako said, it references an instance in form of a prefab or a scene gameobject (any gameobject with the script attached).
they only ever exist on gameobjects and get created by the engine in C++ form. so, it's referencing an instance of the class. that's why you can't reference the script only.