Created
December 6, 2018 14:37
-
-
Save dyguests/3ff662f8cfd714c4d10d5dbfb17f02f4 to your computer and use it in GitHub Desktop.
Unity ComponentUtils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
namespace Utils | |
{ | |
public static class ComponentUtils | |
{ | |
/// <summary> | |
/// 将一个Component复制到另一个GameObject中 | |
/// | |
/// see [https://answers.unity.com/questions/458207/copy-a-component-at-runtime.html] | |
/// 注:Material的复制有问题 | |
/// </summary> | |
/// <param name="original"></param> | |
/// <param name="destination"></param> | |
/// <typeparam name="T"></typeparam> | |
/// <returns></returns> | |
public static T CopyComponent<T>(T original, GameObject destination) where T : Component | |
{ | |
Type type = original.GetType(); | |
var dst = destination.GetComponent(type) as T; | |
if (!dst) dst = destination.AddComponent(type) as T; | |
var fields = type.GetFields(); | |
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment