- Home /
How can I copy all scripts from one gameobject to another in code?
I want to copy all user-written scripts from one gameobject("leftSideObj") to another("rightSideObj"), and I want to do it from a script at runtime. For project-specific reasons, I can't just copy the first gameobject and call that my second one, because the two objects have different meshes, colliders/collider types, etc. Not that I even know if that's possible. I wrote some code that half works, and that illustrates what I really hope exists, but I just don't know the right syntax for it:
MonoBehaviour[] scriptList = leftSideObj.GetComponents<MonoBehaviour>();
foreach (MonoBehaviour script in scriptList)
{
rightSideObj.AddComponent(script.GetType());
Field[] fields = rightSideObj.GetComponent(script.GetType()).GetFields();
foreach (Field field in fields)
{
rightSideObj.GetComponent(script.GetType()).field = leftSideObj.GetComponent(script.GetType()).field;
}
}
It works so far as the line, "rightSideObj.AddComponent(script.GetType());" which is nice, but beyond that, it's just stuff I made up. There is no "Field" type for the public input fields of a script component, at least not called that. But if there is a way to do this, it would really help me out! Does anyone know?
Answer by KyleBlumreisinger · Dec 04, 2017 at 06:46 AM
Man do I feel silly now - I just did more research and testing, and I actually got it working! Here's the finished block of code, if anyone stumbles on this question later and needs it:
MonoBehaviour[] scriptList = leftSideObj.GetComponents<MonoBehaviour>();
foreach (MonoBehaviour script in scriptList)
{
rightSideObj.AddComponent(script.GetType());
System.Reflection.FieldInfo[] fields = script.GetType().GetFields();
foreach (System.Reflection.FieldInfo field in fields)
{
field.SetValue(rightSideObj.GetComponent(script.GetType()), field.GetValue(script));
}
}
Cheers!
Your answer
Follow this Question
Related Questions
enable and disable loop objects in the scene 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Problem with a Unity Scripting example from the scripting manual! 0 Answers
Can I make Money collecting script without attaching it to a object ? I tried but I got error 2 Answers