How to add UnityEvent using Custom Inspector?

Hi, I’m new to custom inspectors so please be patient. Let’s say my code looks like this:

public class ExampleClass : MonoBehaviour
{
    public UnityEvent myEvent;
}

[CustomEditor(typeof(ExampleClass))]
public class EventEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Add event"))
        {
            ...
        }
    }
}

So I have 1 UnityEvent and what I’m trying to do is add another one when I press a button in my custom inspector. I’ve been googling for hours now and I just can’t get it to work.

I’ve tried something like this:

[CustomEditor(typeof(ExampleClass))]
public class EventEditor : Editor
{
    SerializedObject _example;

    void OnEnable()
    {
        SerializedObject _example= new SerializedObject((ExampleClass)target);
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Add event"))
        {
            SerializedProperty sprop = _example.FindProperty("myEvent");
            EditorGUILayout.PropertyField(sprop);
            _example.ApplyModifiedProperties();
        }
    }
}

…but no luck :frowning:

Help!

But what kind of event you would like to use? and what is the final aim? if it is not a top secret project, please give us the context so we can try to think of the best solution for your situation.

–

The final aim is for my game/lvl designer to be able to manipulate objects using unityevents and trigger them as he pleases using colliders. Now he does have one unity event which he uses pretty often but now we need more. So i wanted to give him the ability to create his own with just one button and then figure out how to add public methods which would invoke these events... but i'm stuck on step one :)

–

1 Answer

1

Seems like someone solved it:

Thanks! That's exactly what I needed.

–