Daniel Lip
Daniel Lip

Reputation: 11335

How can I replace a selected objects with a prefab including childs if there are any using searching?

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

public class PrefabReplace : EditorWindow
{
    [SerializeField] private GameObject prefab;
    private bool selectionChanged;
    private string objectsToSearch = "";
    private List<GameObject> foundObjects = new List<GameObject>();
    private List<GameObject> duplicatedObjects = new List<GameObject>();
    private bool searched = false;
    private int count = 0;
    private int countChilds = 0;
    private bool countChildren = false;

    [MenuItem("Tools/Prefab Replace")]
    static void CreateReplaceWithPrefab()
    {
        int width = 340;
        int height = 300;

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

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

    private void OnGUI()
    {
        Searching();
        GUILayout.Space(50);
        Replacing();
    }

    private void Searching()
    {
        GUI.Label(new Rect(10, 20, 150, 20), "Search by name");
        objectsToSearch = GUI.TextField(new Rect(90, 60, 150, 20), objectsToSearch, 25);

        if (objectsToSearch != "")
        {
            GUI.enabled = true;
        }
        else
        {
            GUI.enabled = false;
        }
        GUILayout.Space(40);
        if (GUILayout.Button("Search"))
        {
            foundObjects = new List<GameObject>();
            duplicatedObjects = new List<GameObject>();
            countChildren = true;
            countChilds = 0;
            count = 0;

            foreach (GameObject gameObj in GameObject.FindObjectsOfType<GameObject>())
            {
                if (gameObj.name == objectsToSearch)
                {
                    count += 1;
                    foundObjects.Add(gameObj);
                }
            }

            if (foundObjects.Count > 0)
            {
                searched = true;
            }
            else
            {
                searched = false;
            }
        }

        GUI.enabled = true;
        if (count > 0)
            GUI.TextField(new Rect(90, 85, 60, 15), count.ToString(), 25);

        if (foundObjects.Count > 0 && countChildren == true)
        {
            for (int i = 0; i < foundObjects.Count; i++)
            {
                if (foundObjects[i].transform.childCount > 0)
                {
                    countChilds += foundObjects[i].transform.childCount;
                    //GameObject duplicate = Instantiate(foundObjects[i]);
                    //duplicate.name = foundObjects[i].name;
                    //duplicatedObjects.Add(duplicate);
                }
            }

            countChildren = false;
        }
        GUI.enabled = true;
        if (countChilds > 0)
            GUI.TextField(new Rect(90, 105, 60, 15), countChilds.ToString(), 25);

        GUILayout.Space(100);

        if (foundObjects.Count > 0)
            EditorGUILayout.LabelField("Test");
    }

    private void Replacing()
    {
        GUILayout.Space(20);
        GUILayout.BeginVertical(GUI.skin.box);
        GUILayout.Label("Replacing");
        GUILayout.Space(20);

        prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false);

        var selection = Selection.objects.OfType<GameObject>().ToList();
        if (selectionChanged)
        {
            if (selection.Count == 0)
                GUI.enabled = false;

            for (var i = selection.Count - 1; i >= 0; --i)
            {
                var selectedObject = selection[i];
                if (prefab != null && selection.Count > 0 &&
                    selectedObject.scene.name != null
                    && prefab != PrefabUtility
                    .GetCorrespondingObjectFromSource(selectedObject))
                {
                    GUI.enabled = true;
                }
                else
                {
                    GUI.enabled = false;
                }
            }
        }
        else
        {
            GUI.enabled = false;
        }

        if (GUILayout.Button("Replace"))
        {
            InstantiatePrefab(selection);
            selectionChanged = false;
        }

        GUILayout.Space(10);
        GUI.enabled = true;
        EditorGUILayout.LabelField("Selection count: " + Selection.objects.OfType<GameObject>().Count());

        GUILayout.EndVertical();
    }

    private void OnInspectorUpdate()
    {
        Repaint();
    }

    private void OnSelectionChange()
    {
        selectionChanged = true;
    }

    private void InstantiatePrefab(List<GameObject> selection)
    {
        if (prefab != null && selection.Count > 0)
        {
            for (var i = selection.Count - 1; i >= 0; --i)
            {
                var selected = selection[i];
                SceneManager.SetActiveScene(SceneManager.GetSceneByName(selected.scene.name));

                var prefabType = PrefabUtility.GetPrefabType(prefab);
                GameObject newObject;

                if (prefabType == PrefabType.Prefab)
                {
                    newObject = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
                }
                else
                {
                    newObject = Instantiate(prefab);
                    newObject.name = prefab.name;
                }
                if (newObject == null)
                {
                    Debug.LogError("Error instantiating prefab");
                    break;
                }

                Undo.RegisterCreatedObjectUndo(newObject, "Replace With Prefabs");
                newObject.transform.parent = selected.transform.parent;
                newObject.transform.localPosition = selected.transform.localPosition;
                newObject.transform.localRotation = selected.transform.localRotation;
                newObject.transform.localScale = selected.transform.localScale;
                newObject.transform.SetSiblingIndex(selected.transform.GetSiblingIndex());
                Undo.DestroyObjectImmediate(selected);
            }
        }
    }
}

The searching part find object/s in the hierarchy and if there are any childs it's counting them too.

The replacing part replace a prefab with selection of objects. If for example I selected 20 Cubes and clicked the Replace button it will replace the selected Cubes with the prefab with the same position,rotation,scaling the cubes was.

But it's not replacing childs if there are any.

I need somehow when searching to add to a List/s the parent and childs and keep the hierarchy of each parent and his childs and then when clicking the replace button to replace it will the searching results objects and not with the selection like now and including the childs.

Example if my Hierarchy looks like this:

Cube1
Cube1
Cube1
  Cube1
    Cube1
Cube1

If I'm searching for Cube1 I shold find 6 Cubes and two of them childs. And if for example I will replace them with Sphere prefab the Hierarchy should looks like:

Sphere
Sphere
Sphere
  Sphere
    Sphere
Sphere

What I need to do is to combine the searching part with the replacing part and make that the replacing will include also childs.

Upvotes: 1

Views: 907

Answers (1)

Dave
Dave

Reputation: 2862

You could try something like this:

void ChangeObjectRecursively(Transform t)
{
    for (int i = 0; i < t.childCount; i++)
    {
        ChangeObjectRecursively(t.getChild(i));
    }

    ChangeObject(t.gameObject);
}

Upvotes: 1

Related Questions