- Home /
How make EditorGUILayout.ObjectField get a Monobehaviour from the Assets folder
In a custom editor, I want to let the user select a monobehaviour script from the Assets folder. Unfortunately, I'm not having much luck.
The code I'm using is:
script = EditorGUILayout.ObjectField(script, typeof(MonoBehaviour));
It creates the field, but only let me select GameObjects in the scene.
So, anyone knows how to use the ObjectField to select a monobehaviour from the assets?
Answer by Bunny83 · Jan 27, 2013 at 03:17 AM
A MonoBehaviour script asset is not the same as the MonoBehaviour component. What you need is the MonoScript class. The MonoScript class is basically just a TextAsset which contains the source code, but in addition it has the GetClass function which can be used to access the "MonoBehaviour-type" that is implemented by this script. This type can be used in AddComponent for example.
Keep in mind that MonoScript is an editor class, so don't use it in runtime classes.
Hi! How did you get this working? I can get it to find $$anonymous$$onoscript assets just fine, but how do you convert the type GetClass returns into a $$anonymous$$onobehaviour?
Ok I got it working when I used Object for variable type ins$$anonymous$$d of $$anonymous$$onoBehaviour
@Urre: I'm not sure what you mean a $$anonymous$$onoScript is not an instance of that script, so you can't somehow "convert" it into a $$anonymous$$onoBehaviour. What you can do is using the type you get from GetClass in an AddComponent call. Like this:
//C# (somewhere inside an editor script)
$$anonymous$$onoScript someScriptReference;
// [...]
System.Type monoBehaviourType = someScriptReference.GetClass();
someGameObject.AddComponent(monoBehaviourType);
Yeah, thing is I'm not looking to add it to a GameObject, I can't even see why that would be interesting. What I'm trying to do is make a custom inspector which can list scripts in my project when I click on the Object Picker icon, so, using ObjectField like in the above example, I need to somehow look for $$anonymous$$onoScripts in the project, but then get the value as a $$anonymous$$onoBehaviour. I've since I posted that one figured out you can't even assign scripts by drag & drop to a public $$anonymous$$onobehaviour variable for some reason, so I'm probably going entirely in the wrong direction. The goal is in the end to use FindObjectsOfType(sometype) with sometype being a class type defined by the user in the inspector, but I can't figure that out right now.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Custom Editor: Objectfield clears on play 2 Answers
EditorGUILayout.Knob() !? 0 Answers
Access EditorGUILayout objects 1 Answer