-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComponentUtil.cs
More file actions
56 lines (44 loc) · 1.67 KB
/
ComponentUtil.cs
File metadata and controls
56 lines (44 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
namespace Utils
{
// http://answers.unity3d.com/questions/458207/copy-a-component-at-runtime.html
// http://stackoverflow.com/questions/10261824/how-can-i-get-all-constants-of-a-type-by-reflection
public class ComponentUtil
{
public static T CopyComponent<T>(T original, GameObject destination) where T : Component
{
System.Type type = original.GetType();
var dst = destination.GetComponent(type) as T;
if (!dst) dst = destination.AddComponent(type) as T;
var fields = GetAllFields(type);
foreach (var field in fields)
{
if (field.IsStatic) continue;
field.SetValue(dst, field.GetValue(original));
}
var props = type.GetProperties();
foreach (var prop in props)
{
if (!prop.CanWrite || !prop.CanWrite || prop.Name == "name") continue;
prop.SetValue(dst, prop.GetValue(original, null), null);
}
return dst as T;
}
public static IEnumerable<FieldInfo> GetAllFields(System.Type t)
{
if (t == null)
{
return Enumerable.Empty<FieldInfo>();
}
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.DeclaredOnly;
return t.GetFields(flags).Concat(GetAllFields(t.BaseType));
}
}
}