Skip to content

Commit 24c4406

Browse files
committed
Refactor CopyComponent function to utilize addComponent & EditorUtility.CopySerialized instead of custom logic
1 parent cfa2936 commit 24c4406

1 file changed

Lines changed: 4 additions & 23 deletions

File tree

Scripts/Utilities/ObjectUtils.cs

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -202,30 +202,11 @@ public static Component AddComponent(Type type, GameObject go)
202202

203203
public static T CopyComponent<T>(T sourceComponent, GameObject targetGameObject) where T : Component
204204
{
205-
Type sourceType = sourceComponent.GetType();
206-
var targetComponent = targetGameObject.GetComponent(sourceType) as T;
207-
if (!targetComponent)
208-
targetComponent = targetGameObject.AddComponent(sourceType) as T;
205+
var sourceType = sourceComponent.GetType();
206+
var clonedTargetComponent = AddComponent(sourceType, targetGameObject);
207+
EditorUtility.CopySerialized(sourceComponent, clonedTargetComponent);
209208

210-
var fields = sourceType.GetFields();
211-
foreach (var field in fields)
212-
{
213-
if (field.IsStatic)
214-
continue;
215-
216-
field.SetValue(targetComponent, field.GetValue(sourceComponent));
217-
}
218-
219-
var properties = sourceType.GetProperties();
220-
foreach (var property in properties)
221-
{
222-
if (!property.CanWrite || property.Name == "name")
223-
continue;
224-
225-
property.SetValue(targetComponent, property.GetValue(sourceComponent, null), null);
226-
}
227-
228-
return (T)targetComponent;
209+
return (T)clonedTargetComponent;
229210
}
230211

231212
static IEnumerable<Type> GetAssignableTypes(Type type, Func<Type, bool> predicate = null)

0 commit comments

Comments
 (0)