Last active
October 30, 2025 11:50
-
-
Save MisterKidX/db3d7351577e86468d649003984e284a to your computer and use it in GitHub Desktop.
A reflection method for copying components in Unity
This file contains hidden or 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
| 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