Posted By

ravina26 on 11/29/18


Tagged

copy hierarchy all Generic values components c# unity3d GameObject


Versions (?)

Copy Components


 / Published in: C#
 

Copies all components from a selected gameobject in a unity 3d project scene hierarchy to another gameobject, this copies all attached components including their values.

  1. using System;
  2. using UnityEngine;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7.  
  8. public class CopyComponentHelper
  9. {
  10. static Component[] components;
  11.  
  12. [MenuItem("GameObject/My Coustom Menu/Copy Components", false, 0)]
  13. static void Copy_Component()
  14. {
  15. GameObject self = (GameObject)Selection.activeObject;
  16.  
  17. components = self.GetComponents<Component>();
  18. }
  19.  
  20. [MenuItem("GameObject/My Custom Menu/Paste Components", false, 0)]
  21. static void Paste_Component()
  22. {
  23. GameObject self = (GameObject)Selection.activeObject;
  24.  
  25. if(components != null && components.Length > 0)
  26. {
  27. for(int i = 0; i < components.Length; i++)
  28. {
  29. CopyComponent(components[i], self);
  30. }
  31. }
  32. }
  33.  
  34. static void CopyComponent(Component original, GameObject destination)
  35. {
  36. System.Type componentType = original.GetType();
  37. Component copyComponent = destination.AddComponent(componentType);
  38.  
  39. //Fields may be restricted by using System.Reflection.BindingFlags
  40. System.Reflection.FieldInfo[] fields = componentType.GetFields();
  41. foreach(System.Reflection.FieldInfo field in fields)
  42. {
  43. field.SetValue(copyComponent, field.GetValue(original));
  44. }
  45. }
  46. }

Report this snippet  

You need to login to post a comment.