using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEngine.UI; public class ChangeTextAndImage : EditorWindow { [MenuItem("程序/替换层次视图中预制体的文本或图片")] public static void Open() { EditorWindow.GetWindow(typeof(ChangeTextAndImage)); } static GameObject tagetObj; void OnGUI() { GUILayout.Label("Hierarchy 层次视图中的预制体"); if (GUILayout.Button("将Text更换为TextEx")) { ChangeText(); } if (GUILayout.Button("将Image更换为ImageEx")) { ChangeImage(); } } void ChangeText() { //将指定的tagetObj预制体中的所有Text更换为TextEx //Selection.activeObject; tagetObj = Selection.activeObject as GameObject; if (tagetObj == null) { Debug.LogError("请将预制体拖到Hierarchy 层次视图 并选中"); return; } Text[] texts = tagetObj.GetComponentsInChildren(true); //将Text[]转成 List List golist = new List(); foreach (var item in texts) { golist.Add(item.gameObject); } for (int i = 0; i < golist.Count; i++) { var go = golist[i]; Text text = go.GetComponent(); if (text as TextEx != null) { continue; } var textContent = text.text; var textFontSize = text.fontSize; //删除Text DestroyImmediate(text); TextEx textEx = go.AddMissingComponent(); textEx.text = textContent; textEx.font = FontUtility.preferred; textEx.fontSize = textFontSize; textEx.raycastTarget = false; textEx.alignment = TextAnchor.MiddleCenter; textEx.horizontalOverflow = HorizontalWrapMode.Wrap; textEx.verticalOverflow = VerticalWrapMode.Truncate; textEx.resizeTextForBestFit = true; textEx.resizeTextMinSize = 10; textEx.resizeTextMaxSize = textFontSize; } } void ChangeImage() { //将指定的tagetObj预制体中的所有Image更换为ImageEx //Selection.activeObject; tagetObj = Selection.activeObject as GameObject; if (tagetObj == null) { Debug.LogError("请将预制体拖到Hierarchy 层次视图 并选中"); return; } Image[] images = tagetObj.GetComponentsInChildren(true); //将Image[]转成 List List golist = new List(); foreach (var item in images) { golist.Add(item.gameObject); } for (int i = 0; i < golist.Count; i++) { var go = golist[i]; Image image = go.GetComponent(); if (image as ImageEx != null) { continue; } var imageSprite = image.sprite; var imageColor = image.color; //删除Image DestroyImmediate(image); ImageEx imageEx = go.AddMissingComponent(); imageEx.sprite = imageSprite; imageEx.raycastTarget = false; } } }