Unity3D 一键更换场景物体

来源:互联网 发布:颂党恩 知党史 征文 编辑:程序博客网 时间:2024/05/08 23:42
作为一名高贵的程序猿,通过代码让电脑代替自己的工作是我们存在的意义。
不管要更换的是什么东西,我们都可以用一个prefab把它们替换掉。

都在代码里,走一个~

using UnityEngine;using System.Collections;using UnityEditor;using System.Collections.Generic;/// <summary>/// 改变Prefab/// 注:通过名字匹配搜索被替换目标/// (被选中物体的所有子物体.name包含newPrefab.name则替换)/// </summary>public class ChangePrefab : EditorWindow {    [MenuItem("DuanTools/换Prefab")]    public static void Open()    {        EditorWindow.GetWindow(typeof(ChangePrefab));    }    public GameObject newPrefab;    static GameObject tonewPrefab;    void OnGUI()    {        newPrefab = (GameObject)EditorGUILayout.ObjectField(newPrefab, typeof(GameObject),true, GUILayout.MinWidth(100f));        tonewPrefab = newPrefab;        if (isChange)        {            GUILayout.Button("正在变...");        }        else        {            if (GUILayout.Button("变变变!"))                Change();        }    }    static bool isChange = false;    public static void Change()    {        if (tonewPrefab == null)            return;        isChange = true;        List<GameObject> destroy = new List<GameObject>();        Object[] labels = Selection.GetFiltered(typeof(GameObject), SelectionMode.Deep);        foreach (Object item in labels)        {            GameObject tempGO = (GameObject)item; // (GameObject)item;            //只要搜到的物体包含新Prefab的名字,就会被替换            if (tempGO.name.Contains(tonewPrefab.name))            {                GameObject newGO = (GameObject)Instantiate(tonewPrefab);                newGO.transform.SetParent(tempGO.transform.parent);                newGO.name = tempGO.name;                newGO.transform.localPosition = tempGO.transform.localPosition;                newGO.transform.localRotation = tempGO.transform.localRotation;                newGO.transform.localScale = tempGO.transform.localScale;                destroy.Add(tempGO);            }        }        foreach (GameObject item in destroy)        {            DestroyImmediate(item.gameObject);        }        isChange = false;    }}

下面是使用方法:
首先打开刚才制作的编辑器窗口,选择一个要替换成的Prefab。
然后在游戏场景内寻则要被替换物体的最父级。
点击“变变变”,所有包含新prefab名字的场景内物体都会被替换掉了。

0 0
原创粉丝点击