How to echange a script of a component?

Hi there,

I have the following problem: I have 10k objects using the MonoBehaviour “BaseBehaviour”. Now I have written a derived class “DerivedBehaviour” which is derived from “BaseBehaviour”. Now I want to change the used scripts of every second GameObject, which uses the BaseBehaviour to DerivedBehaviour. I know this can be done in Editor by clicking der circle on the side of the script field, but how can I do this by code? Is there a way doing this with an editor script? Even reflection would be fine. I know its a very hypothetical case, but I had this problem many times. Each time something has been greatly refactored.

Thanks in advance.

Create yourself a editor script like this. Given the fact that this is a one-off script, I would not bother adding more usability - if you need to change types, edit the script before pushing the button.

using System;
using UnityEditor;
using UnityEngine;

public class ReplacementScript: EditorWindow
{
  public ReplacementScript ()
  {
  }

  [MenuItem("Window/Replace Magic")]
  public static void MenuOption ()
  {
    ReplacementScript window = (ReplacementScript)GetWindow (typeof(ReplacementScript));
    window.autoRepaintOnSceneChange = true;
    window.title = "BitGUI Toolbox";
    window.Show ();
  }

  public void OnGUI()
  {
    if (GUI.Button(new Rect(10, 10, 300, 20), "Push Me!"))
    {
      GameObject[] gos = GameObject.FindObjectsOfType(typeof (BaseBehaviour));
      foreach (GameObject go in gos)
      {
        BaseBehaviour oldObject = go.GetComponent<BaseBehaviour>();
        DerivedBehaviour newObject = go.AddComponent<DerivedBehaviour>();

        // copy all properties now
        // ...

        GameObject.DestroyImmediate(oldObject);
      }
    }
  }
}

Thanks for your reply. The posted code snippet would be an adequate solution if there wouldn’t be multiple inheritence levels and a lot of fields which have to be copied. Isn’t there any better way? The proposed solution would mean to write a realy complex (de)serializer for components using relfection.