- 最后登录
- 2019-12-25
- 注册时间
- 2012-8-24
- 阅读权限
- 90
- 积分
- 71088
 
- 纳金币
- 52352
- 精华
- 343
|
作为一名高贵的程序猿,通过代码让电脑代替自己的工作是我们存在的意义。既然我们能一键更换UI字体,那我们肯定也需要一键更换场景内其它物体。
不管要更换的是什么东西,我们都可以用一个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名字的场景内物体都会被替换掉了。
|
|