How to create a UnityAction for changing a property from (c#)

Hi,

I’m trying to script the creation of a UnityAction that will be triggered by an event to change a property (MeshRenderer.material).

I’ve been inspecting the data for a similar event created in the editor, where the UX presented is

Here is the code I’ve come up with, which isn’t quite working correctly

	Material shinyYellow = (Material)Resources.Load < Material>("ShinyYellow");
	MeshRenderer meshRenderer = ihe.GetComponent<MeshRenderer> ();

	PropertyInfo mat = meshRenderer.GetType().GetProperty ("material");
	MethodInfo setter = mat.GetSetMethod ();

	UnityAction<Material> action = System.Delegate.CreateDelegate(typeof(UnityAction<Material>), meshRenderer, setter, true) as UnityAction<Material>;

	UnityEventTools.AddObjectPersistentListener<Material>( ihe.onHandHoverBegin, action, shinyYellow);

From the debugger the action looks to be correctly configured, but the AddObjectPersistentListener is not populating the onHandHoverBegin event correctly.

I’ve inspected the onHandHoverBegin structure in the debugger, with event [0] created by the UX and the event [1] added by the above code. It’s clear that the script created listener is missing UnityAction data such as the method name etc.

Any thoughts on what I am doing wrong ?

I’ve create a simplified version of this solution that should do what you want (granted, I am not pulling the material from Resources but it otherwise does the same thing)

Here is the generic event handler code (it gets subscribed to):

using UnityEngine;
using UnityEngine.Events;

public class EventHandler : MonoBehaviour {

	public UnityEvent OnDoSomething;

	public void SimulateEventTrigger()
	{
		OnDoSomething.Invoke ();
	}
}

And here is the thing that registers, listens, and changes the material:

using UnityEngine;

public class EventSubscriber : MonoBehaviour {

	public EventHandler eventHandler;
	public Material mat;

	MeshRenderer rend;

	// Use this for initialization
	void Start () {
		eventHandler.OnDoSomething.AddListener (ChangeMaterial);
		rend = GetComponent<MeshRenderer> ();
	}
	
	public void ChangeMaterial()
	{
		rend.material = mat;
	}
}

Let me know if I misunderstood something.