Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dyguests
Created December 6, 2018 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyguests/3ff662f8cfd714c4d10d5dbfb17f02f4 to your computer and use it in GitHub Desktop.
Save dyguests/3ff662f8cfd714c4d10d5dbfb17f02f4 to your computer and use it in GitHub Desktop.
Unity ComponentUtils
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