重写hierarchy面板,实现创建Text自动添加content size fitter组件

来源:互联网 发布:拉面说 知乎 编辑:程序博客网 时间:2024/05/16 12:49

最近做项目的时候,发现,在创建UGUI的text的组件的时候,最好能够自动添加一个content size fitter。在百度和网友的帮助下,终于实现了这个功能。


首先上效果图:

  


代码如下:

using UnityEngine;using UnityEditor;using System.Collections;using UnityEngine.UI;public class MyHierarchyMenu : Editor{   [MenuItem("GameObject/UI/CreateText")]   static void CreateText()   {       GameObject go = new GameObject("MyText");       go.AddComponent<RectTransform>();       go.AddComponent<Text>();       go.GetComponent<Text>().color = Color.black;       go.GetComponent<Text>().text = "New Text";       go.GetComponent<Text>().fontSize = 20;       go.AddComponent<ContentSizeFitter>();       go.GetComponent<ContentSizeFitter>().horizontalFit = ContentSizeFitter.FitMode.PreferredSize;       go.GetComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;       go.transform.SetParent(Selection.activeGameObject.transform, true);       go.transform.localPosition = Vector3.zero;       go.transform.localScale = Vector3.one;     }   public override void OnInspectorGUI()   {       base.OnInspectorGUI();       CreateText();   }}

这里说明一下,“GameObject”是右键菜单的开始路径

0 0