Skip to content

Instantly share code, notes, and snippets.

@MisterKidX
Last active October 30, 2025 11:50
Show Gist options
  • Select an option

  • Save MisterKidX/db3d7351577e86468d649003984e284a to your computer and use it in GitHub Desktop.

Select an option

Save MisterKidX/db3d7351577e86468d649003984e284a to your computer and use it in GitHub Desktop.
A reflection method for copying components in Unity
public static T CopyComponent<T>(T component, GameObject destination) where T : Component
{
var type = component.GetType();
var copy = destination.AddComponent(type);
var fields = type.GetRuntimeFields();
// component, gameobject, etc. will override the name and tags, we don't want that
var properties = type.GetRuntimeProperties().Where(p => p.SetMethod != null && p.GetGetMethod(false) != null &&
p.DeclaringType != typeof(GameObject)
&& p.DeclaringType != typeof(Component)
&& p.DeclaringType != typeof(UnityEngine.Object)).ToArray();
foreach (var field in fields) field.SetValue(copy, field.GetValue(component));
foreach (var prop in properties)
{
try
{
prop.SetValue(copy, prop.GetValue(component));
}
catch (ArgumentException) { }
catch (NotSupportedException) { }
}
return copy as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment