- Home /
Retrieving componants and comparing with another
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.
Thanks
You can't "swap" components between GameObjects. You can Remove and Add components on runtime, but there is no way you can move them from one object to another.
Answer by scanzy · Oct 24, 2014 at 01:45 PM
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
Answer by Kiwasi · Oct 24, 2014 at 10:35 AM
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.
Your answer
Follow this Question
Related Questions
AddComponent for RawImage not functioning as expected 0 Answers
GetComponent of ALL clones? 2 Answers
Checking if a component has been removed or not at runtime 1 Answer
Weird GetComponent error 2 Answers