- Home /
Assign a MonoBehaviour script to a variable.
Hi, I need help with this little issue I'm having.
I'm trying to create a custom editor to create spells faster. And I want to be able to assign a script to a variable so I can have default behaviour and custom behaviour.
This is what my editor looks like currently http://prntscr.com/4ibw62
So what I'm trying to do is assign the script to a variable so I can get it's Type and AddComponent it to the created GameObject.
I'm just having trouble with actually assigning the script.
Answer by kacyesp · Aug 31, 2014 at 08:51 PM
void Awake() {
AbilityCreator abilityCreator = GetComponent<AbilityCreator>();
}
Answer by rutter · Aug 31, 2014 at 08:53 PM
assign the script to a variable
It's important to distinguish between classes and objects. If you don't understand the difference, there are thousands of tutorials around the net to explain it. In a nutshell, a class is analogous to a blueprint, and an object is a house built from that blueprint.
So, let's say you have a variable like this:
var myScript : MonoBehaviour;
In that case, myScript
is a reference to a MonoBehaviour object. Possibly one that exists in your scene, or maybe one that's attached to a prefab.
On the other hand, if you're trying to get Unity to serialize a reference to a class, I'm sorry to say that's not supported by Unity's built-in serialization engine. You can put together some workarounds. The simplest is to serialize a string, enum, or some other basic type so that you can use a script to map that back to your desired class.
Unity's serialization is somewhat limited, but you can work within those limitations to accomplish many things.
That is not exactly what I meant, I meant assigning the script to a variable as in how unity does it with selecting a $$anonymous$$onoBehaviour when a script is attached to a GameObject, textfield like thing with the circle to the right.
But I sort of found what I was looking for, it's called $$anonymous$$onoScript. Sort of as in you can't really do a whole lot with it.