Search Unity

Copying a component with a UnityEvent from one object to another

Discussion in 'Scripting' started by KMacro, Mar 18, 2019.

  1. KMacro

    KMacro

    Joined:
    Jan 7, 2019
    Posts:
    48
    I'm trying to take all custom components from one object and copy them to another object. I need to do this because the second object is instantiated at runtime through an AssetBundle.

    It is easy enough to do this with AttachComponent and reflection, however I have hit a bit of a snag when it comes to UnityEvents.

    When a UnityEvent on my original object references a custom script on that same object, I want the copy's UnityEvent to reference the custom script on the copy, not the original.

    Here's my code so far:

    (original and copy are the original component and the one I attach to a separate object at runtime, respectively)
    Code (CSharp):
    1. UnityEvent originalEvent = original.event;
    2. UnityEvent copyEvent = copy.event;
    3. for(int i = 0; i < originalEvent.GetPersistentEventCount(); i ++)
    4. {
    5.     Object target = originalEvent.GetPersistentTarget(i);
    6.     Type targetT = target.GetType();
    7.     var copyTarget = copy.GetComponent(targetT);
    8.     string methodName = originalEvent.GetPersistentMethodName(i);
    9.     MethodInfo methodInfo = UnityEventBase.GetValidMethodInfo(copyTarget, methodName, new Type[] {});
    10.                  
    11.     void Execute()
    12.     {
    13.         methodInfo.Invoke(copyTarget, new object[] {});
    14.     }
    15.  
    16.     copyEvent.AddListener(Execute);
    17. }
    When I debug and inspect my copyEvent after all of this, I see that I have added something to the m_RuntimeCalls List of the event, but I can not inspect whatever this is in my IDE. Furthermore, the method is not called when I do what should invoke it on the copied object.

    Any ideas as to what I could be doing wrong?
     
  2. wesleywh

    wesleywh

    Joined:
    Jun 8, 2014
    Posts:
    19
  3. TelloSoft

    TelloSoft

    Joined:
    Oct 29, 2019
    Posts:
    16
    There is an asset on the unity asset store named Copy Paste UnityEvents, after installing, you will see the nice copy-paste buttons below all of your serialized unity events in the inspector.

    Link To Copy Paste UnityEvents https://assetstore.unity.com/packages/slug/214485