- Home /
How do I copy a CapsulCollider with values to another GameObject?
I'm using UMA so my capsulcollider radius, height and centre are generated at runtime but I need to move the collider up to my parent object. I'm using the following code which I got from this forum but it doesn't copy the values, only adds the component.
Component CopyComponent(Component original, GameObject destination)
{
System.Type type = original.GetType();
Component copy = destination.AddComponent(type);
// Copied fields can be restricted with BindingFlags
System.Reflection.FieldInfo[] fields = type.GetFields();
foreach (System.Reflection.FieldInfo field in fields)
{
Debug.Log(fields.ToString());
field.SetValue(copy, field.GetValue(original));
}
return copy;
}
I use it like this: CopyComponent(umaData.gameObject.GetComponent(), umaData.gameObject.transform.parent.parent.parent.gameObject); Why aren't the values being copied?
don't you need to call SetValue on copy ins$$anonymous$$d of field? (line 10)
you mean? copy.SetValue(copy,field.GetValue(original),copy);
Assets/Scripts/Body.cs(117,23): error CS1061: Type UnityEngine.Component' does not contain a definition for
SetValue' and no extension method SetValue' of type
UnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)
Answer by Wanzyee · Jan 07, 2016 at 10:20 PM
The truth is... The code of "CopyComponent" is VERY RIGHT !!
But, you should see no log when you call it, did you?
That's because, the real reason is, "CapsuleCollider" has no "FieldInfo"... LOL
Use "PropertyInfo" instead, and be careful with the differences between PropertyInfo and FieldInfo.
Thank you very much ! I was wondering why it had 0 fields.