Guest User

Copy component with values

a guest
Nov 15th, 2015
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | None | 0 0
  1.     public static T GetCopyOf<T>(this Component comp, T other) where T : Component
  2.     {
  3.         Type type = comp.GetType();
  4.         if (type != other.GetType()) return null;
  5.         BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
  6.         PropertyInfo[] pinfos = type.GetProperties(flags);
  7.         foreach (var pinfo in pinfos)
  8.         {
  9.             if (pinfo.CanWrite)
  10.             {
  11.                 try
  12.                 {
  13.                     pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
  14.                 }
  15.                 catch
  16.                 {
  17.                     //
  18.                 }
  19.             }
  20.         }
  21.         FieldInfo[] finfos = type.GetFields(flags);
  22.         foreach (var finfo in finfos)
  23.         {
  24.             finfo.SetValue(comp, finfo.GetValue(other));
  25.         }
  26.         return comp as T;
  27.     }
  28.  
  29.     public static T AddComponent<T>(this GameObject go, T toAdd) where T : Component
  30.     {
  31.         return go.AddComponent<T>().GetCopyOf(toAdd) as T;
  32.     }
Advertisement
Add Comment
Please, Sign In to add comment