Unity tool to get UI interface structure

  When developing, it is necessary to obtain the sub-object components of an interface. Although it is very simple, if you type the code every time you obtain it, it is also a very scary thing with one click.

  Now the project uses a tool, click on the interface, and the class that matches the interface structure will be exported. As long as this class is initialized, the components of this interface sub-object can be easily obtained.

  The tool idea is as follows:

  1. Determine the components to be acquired according to the naming of the child objects. For example, the suffix _txt means UILabel, and _go means GameObject.

  2. Traverse all sub-objects and cache the sub-objects with suffixes.

  3. According to the cached sub-object, according to certain string splicing rules, write to the local script.

  An interface structure and the exported interface script results are as follows

  

  As long as the interface resources (Gameobject) are passed in, the components of the sub-object can be directly obtained, which greatly improves the development efficiency. Of course, a series of encapsulation and abstraction are carried out on this script in the project, which are extracted and demonstrated separately here.

  (ps: This is my first project, so I don't know how other projects deal with this problem. If you have better ideas, be sure to tell me)

  Stop gossip and go straight to the dry goods. (The comments are relatively complete, so I won't show my scumbag expression ability)

  Tool script:

using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public  class CreateSprite {
     // The currently operating object 
    private  static GameObject CurGo;
     // The component type corresponding to the suffix 
    public  static Dictionary< string , string > typeMap = new Dictionary< string , string > ()
    {   
        { "sp", typeof(UISprite).Name },
        { "txt", typeof(UILabel).Name },
        { "btn", typeof(UIButton).Name },
        { "go", typeof(GameObject).Name},
    };
    // Script template 
    private  static CreateSpriteUnit info;

    // In the Project window, select the interface to be exported, and then click GameObject/Export Script 
    [MenuItem( " GameObject/Export Script " )]
     public  static  void CreateSpriteAction()
    {
        GameObject[] gameObjects = Selection.gameObjects;
         // Guaranteed to have only one object 
        if (gameObjects.Length== 1 )
        {
            info = new CreateSpriteUnit();
            CurGo = gameObjects[0];
            ReadChild(CurGo.transform);
            info.classname = CurGo.name + "UIPanel";
            info.WtiteClass();
            info = null;
            CurGo = null ;
        }
        else
        {
            EditorUtility.DisplayDialog( " Warning " , " You can only select one GameObject " , " OK " );
        }
    }
    // Traverse all child objects, the GetChild method can only get the first layer of child objects. 
    public  static  void ReadChild(Transform tf)
    {
        foreach (Transform child in tf)
        {
            string[] typeArr = child.name.Split('_');
            if (typeArr.Length > 1)
            {
                string typeKey = typeArr[typeArr.Length - 1];
                if (typeMap.ContainsKey(typeKey))
                {
                    info.evenlist.Add(new UIInfo(child.name, typeKey, buildGameObjectPath(child).Replace(CurGo.name + "/","")));
                }

            }
            if (child.childCount > 0)
            {
                ReadChild(child);
            }
        }
    }
    // Get the path, this path has the current object name, you need to replace the private static string in the header with Replace. 
    BuildGameObjectPath(Transform obj)  
    {
        var buffer = new StringBuilder();

        while (obj != null)
        {
            if (buffer.Length > 0)
                buffer.Insert(0, "/");
            buffer.Insert(0, obj.name);
            obj = obj.parent;
        }
        return buffer.ToString();
    }
}
// The template for exporting the script 
public  class CreateSpriteUnit
{
    public string classname;
    public string template = @"
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class @ClassName
{   
@fields

    public void OnAwake(GameObject viewGO)
    {
@body1
    }

    public void OnDestroy()
    {
@body2
    }
}
" ;
     // All cached sub-object information 
    public List<UIInfo> evenlist = new List<UIInfo> ();
     ///  <summary> 
    /// Write the spliced ​​script locally.
     /// (You can make your own The window supports renaming and selecting paths, and these functions are included in the real project)
     ///  </summary> 
    public  void WtiteClass()
    {
        bool flag = true;
        bool throwOnInvalidBytes = false;
        UTF8Encoding encoding = new UTF8Encoding(flag, throwOnInvalidBytes);
        bool append = false;
        StreamWriter writer = new StreamWriter(Application.dataPath + "/" + classname + ".cs", append, encoding);
        writer.Write(GetClasss());
        writer.Close();
        AssetDatabase.Refresh();
    }
    // Script splicing 
    public  string GetClasss()
    {
        var fields = new StringBuilder();
        var body1 = new StringBuilder();
        var body2 = new StringBuilder();
        for (int i = 0; i < evenlist.Count; i++)
        {
            fields.AppendLine("\t" + evenlist[i].field);
            body1.AppendLine("\t\t" + evenlist[i].body1);
            body2.AppendLine("\t\t" + evenlist[i].body2);
        }
        template = template.Replace("@ClassName", classname).Trim();
        template = template.Replace("@body1", body1.ToString()).Trim();
        template = template.Replace("@body2", body2.ToString()).Trim();
        template = template.Replace("@fields", fields.ToString()).Trim();
        return template;
    }
}
// Sub object information 
public  class UIInfo{
     public  string field;
     public  string body1;
     public  string body2;
     public UIInfo( string name, string typeKey, string path)
    {
        field = string.Format("public {0} {1};", CreateSprite.typeMap[typeKey], name);
        if (typeKey == "go")
        {
            body1 = string.Format("{0} = viewGO.transform.Find(\"{1}\").gameObject;", name, path, CreateSprite.typeMap[typeKey]);
        }
        else
        {
            body1 = string.Format("{0} = viewGO.transform.Find(\"{1}\").GetComponent<{2}>();", name, path, CreateSprite.typeMap[typeKey]);
        }
        body2 = string.Format("{0} = null;", name);
    }
}

 

 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324792298&siteId=291194637