Why when instantiating prefabs it's instantiating clones too and double of the amount given ?

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.SceneManagement;
using UnityEditor;

public static class TransformSaver
{
    [System.Serializable]
    public class Transform
    {
        public string sceneName;
        public string name;
        public UnityEngine.Transform parent;
        public Vector3 pos;
        public Quaternion rot;
        public Vector3 scale;
    }

    //Save Transform
    public static void SaveTransform(UnityEngine.GameObject[] tranformToSave)
    {
        Transform[] trnfrm = new Transform[tranformToSave.Length];
        for (int i = 0; i < trnfrm.Length; i++)
        {
            trnfrm[i] = new Transform();

            trnfrm[i].sceneName = tranformToSave[i].gameObject.scene.name;
            trnfrm[i].name = tranformToSave[i].name;
            trnfrm[i].parent = tranformToSave[i].transform.parent;
            trnfrm[i].pos = tranformToSave[i].transform.position;
            trnfrm[i].rot = tranformToSave[i].transform.rotation;
            trnfrm[i].scale = tranformToSave[i].transform.localScale;
        }

        string jsonTransform = JsonHelper.ToJson(trnfrm, true);
        File.WriteAllText(@"e:\json\json.txt", jsonTransform);
    }

    public static Transform[] LoadTransforms()
    {
        string jsonTransform = File.ReadAllText(@"e:\json\json.txt");
        if (jsonTransform == null)
        {
            return null;
        }

        Transform[] savedTransforms = JsonHelper.FromJson<Transform>(jsonTransform);

        return savedTransforms;
    }

    //Load Transform
    public static UnityEngine.Transform[] LoadTransform(bool usePrefab, GameObject prefab, bool useSceneName, string sceneName)
    {
        string jsonTransform = File.ReadAllText(@"e:\json\json.txt");
        if (jsonTransform == null)
        {
            return null;
        }

        Transform[] savedTransforms = JsonHelper.FromJson<Transform>(jsonTransform);
        GameObject[] gameObjects = new GameObject[savedTransforms.Length];
        UnityEngine.Transform[] loadedTransforms = new UnityEngine.Transform[savedTransforms.Length];

        for (int i = 0; i < savedTransforms.Length; i++)
        {
            try
            {
                if (useSceneName)
                {
                    SceneManager.SetActiveScene(SceneManager.GetSceneByName(sceneName));
                }
                else
                {
                    SceneManager.SetActiveScene(SceneManager.GetSceneByName(savedTransforms[i].sceneName));
                }
            }
            catch
            {

            }
            if (usePrefab == true && prefab != null)
            {
                UnityEngine.Object.Instantiate(prefab, savedTransforms[i].pos,
                    savedTransforms[i].rot, savedTransforms[i].parent);
            }
            else
            {
                gameObjects[i] = new GameObject();

                loadedTransforms[i] = gameObjects[i].transform;

                loadedTransforms[i].name = savedTransforms[i].name;
                loadedTransforms[i].parent = savedTransforms[i].parent;
                loadedTransforms[i].position = savedTransforms[i].pos;
                loadedTransforms[i].rotation = savedTransforms[i].rot;
                loadedTransforms[i].localScale = savedTransforms[i].scale;
            }
        }
        return loadedTransforms;
    }
}

And editorwindow script :

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class SaveTransformsInfo : EditorWindow
{
    public GameObject source;

    [MenuItem("Tools/Save Transforms")]
    private static void CreateReplaceWithPrefab()
    {
        const int width = 340;
        const int height = 70;

        var x = (Screen.currentResolution.width - width) / 2;
        var y = (Screen.currentResolution.height - height) / 2;

        GetWindow<SaveTransformsInfo>().position = new Rect(x, y, width, height);
    }

    private void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Select Prefab", GUILayout.Width(80));
        source = (GameObject)EditorGUILayout.ObjectField(source, typeof(GameObject), true, GUILayout.ExpandWidth(true));
        EditorGUILayout.EndHorizontal();

        GUILayout.Space(35);

        if (GUILayout.Button("Save Transforms"))
        {
            TransformSaver.SaveTransform(Selection.gameObjects);
        }

        GUILayout.Space(2);

        if (GUILayout.Button("Load Transforms"))
        {
            TransformSaver.LoadTransform(true, source, false, "");
        }

    }
}

For example I’m selecting 20 gameobjects in the hierarchy in the editor.
Then clicking the button Save Transforms it’s creating json file with the information of the 20 gameobjects transforms.

Then I select a prefab and click the button Load Transforms.

Now it’s creating the 20 new prefabs I can see on this line that it contains 20 gameobjects :

for (int i = 0; i < savedTransforms.Length; i++)

The Length of the savedTransforms is 20.

But in the end there are the new 20 prefabs and more 20 Clones.
And when I select some of the new 20 prefabs in the editor in hierarchy I see that some of them are the same also as Clones.

And for each new prefab he make another clone that sit under it with wrong rotation and position and it also part of the new/clones prefabs.

I can’t figure out this mess.

In this screenshot on the top left the door on red is the new created prefab this is a good created prefab in same old transform position and rotation. But under it there is another door in red a Cloned one that is in wrong position and rotation.

And on the right the black objects are the new created prefabs. You can see there are too many prefabs.
Those above are the new ones and should be fine and those clones.

I can’t figure out what is going on.

The main goal is to select gameobjects and then to replace them with new prefabs created by one selected prefab.

Not sure what the cause of your problem is but for this line of code:
gameObjects *= new GameObject();*
You should always use the Instantiate method to create new GameObjects. Otherwise they will not be initialized properly.
Edit: Actually what I said above may not be true. I think it may actually only be monobehaviours that you cannot use “new” to create.
Have you used a Debug.Log to make sure that your LoadTransforms method is only called once? Have you logged the number of loop iterations(i.e SavedTransorms I guess) that actually occur?

Is JsonHelper.FromJson your own code? My Googling isn’t turning that up, and the way you’re calling it seems a bit weird.

How sure are you that you are correctly serializing and deserializing the parents of your transforms? I would have thought you’d need to do something more complicated than that to get a safely-serializable reference. I’m not sure how that could cause the exact symptoms you’re describing, but I wouldn’t be utterly shocked if carelessly deserializing UnityEngine.Transform somehow resulted in you getting extra game objects in your scene.

I did some tests and found the problem. Not a solution but at least the problem so far.
When I filter in the hierarchy search bar by name the objects I want to replace with a prefab I’m getting this results :

And then I did the prefab replace for all this objects.
But then I noticed that this are parents and childs :

This is a structure of a door :

And here is the problem :

Wall_Door_Long_01 is parent that inside have a child with the same name Wall_Door_Long_01
In my tests I found that if I replace only the parent Wall_Door_Long_01 it’s replacing fine but if I replace also the child Wall_Door_Long_01 it’s making the problem.

Somehow in the script I need to check if it’s the same name what is the parent ?
Another problem is that the parent Wall_Door_long_01 is also a child of Corridor_Window_07 so how can I know that the first Wall_Door_Long_01 is a parent of the child Wall_Door_Long_01 ?

And I changed the scripts :

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine.SceneManagement;
using UnityEditor;

public static class TransformSaver
{
   [System.Serializable]
   public class Transform
   {
       public string sceneName;
       public string name;
       public UnityEngine.Transform parent;
       public Vector3 pos;
       public Quaternion rot;
       public Vector3 scale;
   }

   //Save Transform
   public static void SaveTransform(UnityEngine.GameObject[] tranformToSave)
   {
       Transform[] trnfrm = new Transform[tranformToSave.Length];
       for (int i = 0; i < trnfrm.Length; i++)
       {
           trnfrm[i] = new Transform();

           trnfrm[i].sceneName = tranformToSave[i].gameObject.scene.name;
           trnfrm[i].name = tranformToSave[i].name;
           trnfrm[i].parent = tranformToSave[i].transform.parent;
           trnfrm[i].pos = tranformToSave[i].transform.position;
           trnfrm[i].rot = tranformToSave[i].transform.rotation;
           trnfrm[i].scale = tranformToSave[i].transform.localScale;
       }

       string jsonTransform = JsonHelper.ToJson(trnfrm, true);
       File.WriteAllText(@"e:\json\json.txt", jsonTransform);
   }

   public static Transform[] LoadTransforms()
   {
       string jsonTransform = File.ReadAllText(@"e:\json\json.txt");
       if (jsonTransform == null)
       {
           return null;
       }

       Transform[] savedTransforms = JsonHelper.FromJson<Transform>(jsonTransform);

       return savedTransforms;
   }

   //Load Transform
   public static Transform[] LoadTransform(bool usePrefab, GameObject prefab, bool useSceneName, string sceneName)
   {
       string jsonTransform = File.ReadAllText(@"e:\json\json.txt");
       if (jsonTransform == null)
       {
           return null;
       }

       Transform[] savedTransforms = JsonHelper.FromJson<Transform>(jsonTransform);

       for (int i = 0; i < savedTransforms.Length; i++)
       {
           try
           {
               if (useSceneName)
               {
                   SceneManager.SetActiveScene(SceneManager.GetSceneByName(sceneName));
               }
               else
               {
                   SceneManager.SetActiveScene(SceneManager.GetSceneByName(savedTransforms[i].sceneName));
               }
           }

           if (usePrefab == true && prefab != null)
           {
               GameObject go = UnityEngine.Object.Instantiate(prefab);

               go.transform.position = savedTransforms[i].pos;
               go.transform.rotation = savedTransforms[i].rot;
               go.transform.transform.SetParent(savedTransforms[i].parent);

           }
       }
       return savedTransforms;
   }
}

And the editorwindow :

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class SaveTransformsInfo : EditorWindow
{
   public GameObject source;

   [MenuItem("Tools/Save Transforms")]
   private static void CreateReplaceWithPrefab()
   {
       const int width = 340;
       const int height = 70;

       var x = (Screen.currentResolution.width - width) / 2;
       var y = (Screen.currentResolution.height - height) / 2;

       GetWindow<SaveTransformsInfo>().position = new Rect(x, y, width, height);
   }

   private void OnGUI()
   {
       EditorGUILayout.BeginHorizontal();
       EditorGUILayout.LabelField("Select Prefab", GUILayout.Width(80));
       source = (GameObject)EditorGUILayout.ObjectField(source, typeof(GameObject), true, GUILayout.ExpandWidth(true));
       EditorGUILayout.EndHorizontal();

       GUILayout.Space(35);

       if (GUILayout.Button("Save Transforms"))
       {
           TransformSaver.SaveTransform(Selection.gameObjects);
       }

       GUILayout.Space(2);

       if (GUILayout.Button("Load Transforms"))
       {
           TransformSaver.LoadTransform(true, source, false, "");
       }
   }
}

So I know what is the problem the mess with the objects have same name and some parents some childs.
But I don’t yet how to solve it. I have to refactor the TransformSaver to be able to manage this kind of situations with parents and childs. but not sure yet how to do it.