Hi all, i was wondering if anyone could help me go about retrieving componants from a target object and comparing it with another referenced object. I have noticed the getComponents() method, but i keep getting errors when implementing it. My aim is to retrieve the components of one object as a list/array , that way i can dynamically change them at runtime, as in swap components between the seperate objects.
If you want to copy components from a gameobject to another you’ll have to use Reflection:
//foreach component in source
foreach (Component original in source.GetComponents<Component>() )
{
//if not transform (not to be copied)
if (original.GetType() != typeof(Transform))
{
//adds component
Component copied = target.AddComponent(original.GetType());
//gets fields
foreach (FieldInfo info in original.GetType().GetFields())
{
//and copies fields
info.SetValue(copied, info.GetValue(original));
}
}
}
and add “using System.Reflection;” at the top of your code
You will need to overload the == operator, or provide some other method for comparison. Out of the box Unity compares components by checking if the references are equal.