I could only find two way to do this currently, and I don’t know any details about these two implementations.Are they equivalent? Is there any other better way?
UnityAction ActionToUnityAction(Action source)
{
return new UnityAction(source);
}
UnityAction ActionToUnityAction2(Action source)
{
return () => source();
}
Two different delegates types are just that: two completely different types, and their only common type is System.Delegate. There’s no way to directly cast between them. But you can instance one from another delegate with a matching signature.
Too bad that Unity always reinvents their own types instead of using the existing and well known types from the standard
I would go with the first option. The second one feels very hacky to me, and introduces bloat to the stack trace:
new UnityAction(action):
Test
UnityEngine.Debug:Log (object)
Test:MyMethod () (at Assets/Test.cs:24)
Test:Start () (at Assets/Test.cs:19)
() => action():
Test
UnityEngine.Debug:Log (object)
Test:MyMethod () (at Assets/Test.cs:24)
DelegateUtility/<>c__DisplayClass1_0:<ActionToUnityAction2>b__0 () (at Assets/DelegateUtility.cs:8)
Test:Start () (at Assets/Test.cs:20)
Another half-decent option is UnityAction unityAction = action.Invoke, which results in a stack trace identical to that of the first option:
action.Invoke:
Test
UnityEngine.Debug:Log (object)
Test:MyMethod () (at Assets/Test.cs:24)
Test:Start () (at Assets/Test.cs:21)