- Home /
Can I move component of one gameobject to other.
Can I move component of one gameobject to other gameobject using c#.
Answer by Cherno · Nov 28, 2014 at 03:27 PM
This will copy the values from one component to another of the same type. Substitute YourComponentType with the type of component which needs to be copied.
public CopyClassValues(YourCompomentType sourceComp, YourCompomentType targetComp) {
FieldInfo[] sourceFields = sourceComp.GetType().GetFields(BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
int i = 0;
for(i = 0; i < sourceFields.Length; i++) {
var value = sourceFields[i].GetValue(sourceComp);
sourceFields[i].SetValue(targetComp, value);
}
}
Hi, if what you want is done in the Editor and not in the standalone game, you can also use : http://docs.unity3d.com/ScriptReference/EditorUtility.CopySerialized.html
Note that this solution is a workaround for a few common cases, but doesn't work in general. The problem is that any references to the original object (sourceComp) from elsewhere will not automatically update to point to the new copy. As such, this process does not function like a "move".
Answer by YoungDeveloper · Jul 03, 2014 at 10:49 AM
Sure you can, getcomponent and addcomponent, cache the existing component, add it on other GO, then remove it.
http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html
This will create a new component and add that to the gameobject, it won't copy all the values of the previous component.
You are wrong @Tigran "cache the existing component, add it on other GameObject"
@levoTNTO Take a look at the AddComponent function, you only specify a type of the component, you can't pass the object to be copied.
Answer by sonnyb · Nov 08, 2018 at 04:56 PM
No, there is no way to move a component to a different GameObject.
There are workarounds (as explained by other answers) that are likely sufficient for many cases, but there are some limitations.
Your answer
Follow this Question
Related Questions
Gameobjects move towards a moving object c# 1 Answer
Moving GameObject to various position ? 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer