How to change target of UnityEvent

I am using UnityEvents to prepare scripts that will run later. My level designer sets a prefab in them and selects the correct method to run later. At runtime, I now need to accept arguments.

I used to simple get the name (string) of a method and Invoke that on the new object. Unfortunately I can’t get the parameters this way. The real goal is to change the target, but there are no setters for UnityEvents. I could easily call the right thing using reflection, but there isn’t a getter for parameters either.

Anyone has faced a similar problem with UnityEvents? Are there extra methods that I missed? Maybe some stuff in UnityInternal?

Use black magic…

Ok, jokes aside, you can retrieve the parameters but I wouldn’t recommend it. I wont post my code here because it is ugly and dangerous and will get trashed by experienced users. I also wouldn’t want anyone to think this is OK, it is evil.

I did the responsible thing and opened up a feature request. You can vote it up if you need this, but we all know these requests never get implemented so don’t waste your time.
https://feedback.unity3d.com/suggestions/unityevents-add-setter-for-m-target-and-slash-or-getter-for-m-arguments

The method you described, uses a Hashtable. You can implement a similar solution like that using the official tutorial here.

You can also see more about that on the official page here or on that awesome thread here.

About the arguments… you probably are looking for some custom UnityEvents like the ones below:

using UnityEngine;
using UnityEngine.Events;
using System;

[Serializable]
public class UnityEventGameObject : UnityEvent<GameObject> { }

[Serializable]
public class UnityEventTransform : UnityEvent<Transform> { }

[Serializable]
public class UnityEventVector3 : UnityEvent<Vector3> { }

[Serializable]
public class UnityEventVector2 : UnityEvent<Vector2> { }

[Serializable]
public class UnityEventString : UnityEvent<string> { }

[Serializable]
public class UnityEventFloat : UnityEvent<float> { }

[Serializable]
public class UnityEventInt : UnityEvent<int> { }

[Serializable]
public class UnityEventBool : UnityEvent<bool> { }

I use UnityEditor.Events.UnityEventsTools.AddPersistentListener();

Check this docs.