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 ( MonoBehaviour
s ), 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):
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(ScriptManager))]
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.
#pragma strict
public var testArray : MonoScript[]; //Add a script in Editor
function Update ()
{
if(Input.GetKeyDown(KeyCode.J))
{
gameObject.AddComponent(testArray[0].name);
}
}