My question is, if there’s a data type for scripts as objects.
If possible, I’d like to create a public variable containing all the scripts attached to an object, which can be modified in the Unity editor. Pretty much like an enum.
And after that, also a menu containing the methods of the selected script.
It would be pretty much the same as the method selection for buttons in the new UI system.
How can I achieve this in Unity?
Thanks in advance!
Yes, you can achieve this and you will need reflection. There really isn’t a quick answer, so I’ll make an example. (You can gather a list of attached scripts (
MonoBehaviours ), but that won’t really help you with a popup (like an enum).)
Instead, let’s say this is your main class:
public class ScriptManager : MonoBehaviour
public MonoBehaviour selectedScript;
public string selectedMethod;
Then the respective editor (placed in Editor/ folder):
public class ScriptManagerEditor : Editor
public override void OnInspectorGUI()
ScriptManager manager = (ScriptManager)target;
MonoBehaviour scripts = manager.GetComponents<MonoBehaviour>();
string scriptNames = scripts.Select(s => s.GetType().Name).ToArray();
int newIndex = EditorGUILayout.Popup("Script", scripts.ToList().IndexOf(manager.selectedScript), scriptNames);
if (newIndex >= 0)
manager.selectedScript = scripts[newIndex];
if (manager.selectedScript != null)
MethodInfo methods = manager.selectedScript.GetType().GetMethods().Where(m => m.DeclaringType == manager.selectedScript.GetType()).ToArray();
string methodNames = methods.Select(m => m.Name).ToArray();
int methodIndex = EditorGUILayout.Popup("Method", methodNames.ToList().IndexOf(manager.selectedMethod), methodNames);
if (methodIndex >= 0)
manager.selectedMethod = methodNames[methodIndex];
With this you can select any attached script and choose any (public, directly implemented) method. Should look like this:
Although above code is very short, there is a LOT of stuff happening here. I’m afraid don’t really have the time to comment/explain it all.
Also, the new UI system has source code publicly available so you could grab their code.
I’ve tested this idea and it works (in Editor). Sorry, it’s in uJS.
public var testArray : MonoScript; //Add a script in Editor
function Update ()