Unity Editor編輯器代碼修改物體屬性(大小、組件、圖片)

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

public class ScaleOne : EditorWindow
{
    //設置gameobject的Scale
    [MenuItem("Shen/ScaleOne")]
    public static void SetScale()
    {
        foreach (var go in Selection.gameObjects)
        {
            Transform[] gos = go.GetComponentsInChildren<Transform>(true);
            int i = 0;
            foreach (Transform goo in gos)
            {
                if (goo.transform.localScale != Vector3.one)
                {
                    Debug.Log("<color=darkblue>" + goo.name + "</color>" + i);
                    goo.transform.localScale = Vector3.one;
                    i++;
                }
            }
        }
    }

    //移除掉Rigibody組件
    [MenuItem("Shen/RemoveRigibody")]
    public static void RemoveRigibody()
    {
        foreach (var go in Selection.gameObjects)
        {
            Transform[] gos = go.GetComponentsInChildren<Transform>(true);
            int i = 0;
            foreach (Transform goo in gos)
            {
                if (goo.GetComponent<Rigidbody>() != null)
                {
                    Debug.Log("Destroy" + " Rigibody " + "<color=red>"
                        + goo.parent.parent.parent.name + "/"
                        + goo.parent.parent.name + "/"
                        + goo.parent.name + "/"
                        + go.name + "</color>" + i);
                    DestroyImmediate(goo.GetComponent<Rigidbody>());
                    i++;
                }
            }
        }
    }

    //設置list位置(設置我專門創建的物體的位置)
    [MenuItem("Shen/SetListPos")]
    public static void SetListPos()
    {
        foreach (GameObject go in Selection.gameObjects)
        {
            if (go.name == "button_list")
            {
                go.transform.localPosition = new Vector3(-477, 209, 0);
                int count = go.transform.childCount;
                for (int i = 0; i < count; i++)
                {
                    go.transform.GetChild(i).localPosition = new Vector3(0, -i * 62, 0);
                    go.transform.GetChild(i).gameObject.AddComponent<BoxCollider>();
                    go.transform.GetChild(i).GetComponent<BoxCollider>().center = new Vector3(0, 0, 0);
                    go.transform.GetChild(i).GetComponent<BoxCollider>().size = new Vector3(182, 62, 0);
                    if (go.transform.GetChild(i).GetComponent<UIPanel>() != null)
                    {
                        DestroyImmediate(go.transform.GetChild(i).GetComponent<UIPanel>());
                    }

                    if (go.transform.GetChild(i).childCount == 0)
                    {
                        UIAtlas atlaser = AssetDatabase.LoadAssetAtPath(@"Assets/res/atlas/shared/CommonAtlas.prefab", typeof(UIAtlas)) as UIAtlas;

                        for (int k = 0; k < 3; k++)
                        {
                            GameObject go1 = InstantiateEmpetyGameObject(go.transform.GetChild(i));
                            go1.name = k == 0 ? "Sprite0" : (k == 1 ? "Sprite1" : "effect");
                            go1.AddComponent<UISprite>();
                            go1.GetComponent<UISprite>().atlas = atlaser;
                            go1.GetComponent<UISprite>().spriteName = k == 0 ? "phtyys_001" : (k == 1 ? "phtyys_002" : "ty_js_iconred");
                            go1.GetComponent<UISprite>().MakePixelPerfect();
                            go1.GetComponent<UISprite>().depth = k == 0 ? 0 : (k == 1 ? 2 : 4);
                            go1.transform.localPosition = k == 0 ? Vector3.one : (k == 1 ? Vector3.one : new Vector3(80, 20, 0));
                        }

                        for (int j = 0; j < 2; j++)
                        {
                            GameObject gogo = InstantiateEmpetyGameObject(go.transform.GetChild(i).GetChild(j));
                            gogo.name = "Label";
                            gogo.transform.localPosition = new Vector3((j == 0) ? -14 : 0, 0, 0);
                            gogo.AddComponent<UILabel>();
                            Font fonter = AssetDatabase.LoadAssetAtPath(@"Assets/res/font/myfont.TTF", typeof(Font)) as Font;
                            gogo.GetComponent<UILabel>().trueTypeFont = fonter;
                            gogo.GetComponent<UILabel>().text = "123";
                            gogo.GetComponent<UILabel>().applyGradient = false;
                            gogo.GetComponent<UILabel>().overflowMethod = UILabel.Overflow.ResizeFreely;
                            gogo.GetComponent<UILabel>().effectStyle = UILabel.Effect.None;
                            gogo.GetComponent<UILabel>().fontSize = (j == 0) ? 20 : 22;
                            gogo.GetComponent<UILabel>().color = (j == 0) ?
                                new Color(Convert.ToInt32("0x60", 16) / 255.0f, Convert.ToInt32("0x7e", 16) / 255.0f, Convert.ToInt32("0x8f", 16) / 255.0f)
                                : Color.white;
                            gogo.GetComponent<UILabel>().depth = (j == 0) ? 1 : 3;
                        }
                    }
                }
            }
        }
    }

    static GameObject InstantiateEmpetyGameObject(Transform parenter)
    {
        GameObject gogo = new GameObject("Empty");
        gogo.transform.parent = parenter;
        return gogo;
    }

    //設置位置從float型變爲int型
    [MenuItem("Shen/SetPosInt")]
    public static void SetPosInt()
    {
        foreach (Transform tran in Selection.transforms)
        {
            Transform[] trans = tran.GetComponentsInChildren<Transform>();
            foreach (Transform tr in trans)
            {
                if (tr.localPosition.x % 1 != 0 || tr.localPosition.y % 1 != 0)
                {
                    float x = tr.localPosition.x;
                    float y = tr.localPosition.y;
                    Debug.Log(tr.name + " localPosition:" + tr.localPosition);
                    tr.localPosition = new Vector3((float)Math.Round(x), (float)Math.Round(y), 0);
                }
            }
        }
    }

    //設置UILabel上透明屬性
    [MenuItem("Shen/CheckLan")]
    public static void CheckLan()
    {
        foreach (GameObject go in Selection.gameObjects)
        {
            UILabel[] labels = go.GetComponentsInChildren<UILabel>();
            foreach (UILabel label in labels)
            {
                label.alpha = 1f;
            }
        }
    }

    //設置圖片的精靈sprite
    [MenuItem("Shen/ChangeBtnPicture")]
    public static void ChangeBtnPicture()
    {
        foreach (Transform tran in Selection.transforms)
        {
            UISprite[] sprites = tran.GetComponentsInChildren<UISprite>();
            foreach (UISprite sprite in sprites)
            {
                if (sprite.spriteName == "abc")
                {
                    sprite.spriteName = "cba";
                    Debug.Log("Change Picture: " + sprite.transform.parent.name + "/" + sprite.name);
                }
                else if (sprite.spriteName == "nih")
                {
                    sprite.spriteName = "hin";
                    Debug.Log("Change Picture: " + sprite.transform.parent.name + "/" + sprite.name);
                }
            }
        }
    }

    //移除UIWidget組件的錨點
    [MenuItem("Shen/RemoveAnchor")]
    public static void RemoveAnchor()
    {
        foreach (GameObject tran in Selection.gameObjects)
        {
            UIWidget[] widgets = tran.GetComponentsInChildren<UIWidget>();
            foreach (UIWidget widget in widgets)
            {
                widget.SetAnchor(null, 0, 0, 0, 0);
            }
        }
    }

    //設置UISprite圖片的大小變爲原本大小
    [MenuItem("Shen/PcitureSnap")]
    public static void PcitureSnap()
    {
        foreach (GameObject tran in Selection.gameObjects)
        {
            UISprite[] sprites = tran.GetComponentsInChildren<UISprite>();
            foreach (UISprite sprite in sprites)
            {
                sprite.MakePixelPerfect();
            }
        }
    }


    public string fullPath = "Assets/prefabs/";
    MonoScript scriptObj = null;
    int loopCount = 0;
    List<Transform> results = new List<Transform>();
    static ScaleOne window;
    string m_msg = "";
    string m_find_sprite = "";
    string m_find_atlas_sprite = "";
    GameObject m_find_obj;

    //打開editor窗口
    [MenuItem("Shen/Find Script")]
    static void Execute()
    {
        if (window == null)
        {
            window = (ScaleOne)GetWindow(typeof(ScaleOne));
        }
        window.Show();
    }
    private void OnGUI()
    {
        //---------------------------------------------------
        GUILayout.Label("查找所有帶此腳本的預製體。拖入腳本:");
        scriptObj = (MonoScript)EditorGUILayout.ObjectField(scriptObj, typeof(MonoScript), true);
        if (GUILayout.Button("Find"))
        {
            results.Clear();
            loopCount = 0;
            Debug.Log("開始查找.");
            FindScript();
        }

        //---------------------------------------------------
        GUILayout.Label("\n查找選擇物體及子物體腳本里的物體");
        m_find_obj = EditorGUILayout.ObjectField(m_find_obj, typeof(GameObject), true) as GameObject;
        GUILayout.BeginHorizontal();
        bool isToFind = false;
        isToFind = GUILayout.Button("查找", GUILayout.Width(120f));
        GUILayout.EndHorizontal();
        if (isToFind)
        {
            if (Selection.gameObjects == null)
            {
                Debug.LogError("沒有選中任何物體!");
                return;
            }
            bool isFinded = false;
            foreach (GameObject select_obj in Selection.gameObjects)
            {
                Base[] all_scripts = select_obj.GetComponents<Base>();
                if (all_scripts == null || all_scripts.Length == 0)
                {
                    Debug.LogError("此物體及所有子物體沒有附帶腳本!");
                    return;
                }
                foreach (var one_script in all_scripts)
                {
                    int i = 0;
                    foreach (System.Reflection.FieldInfo pi in one_script.GetType().GetFields())
                    {
                        i++;

                        if (pi.GetValue(one_script) == null || !pi.GetValue(one_script).Equals(m_find_obj))
                        {
                            continue;
                        }
                        else
                        {
                            Debug.LogError("找到了 \"" + m_find_obj.name + "\" ! \n在 " + one_script + " 腳本:第" + i + "個:" + pi.Name.Split(' ')[0]);
                            isFinded = true;
                        }
                    }
                }
            }
            if (!isFinded)
            {
                Debug.LogError("Opps,沒有找到 \" => m_find_obj.name \"");
            }
        }

        //----------------------------------------------------
        GUILayout.Label("\n查找所有帶有此Sprite名字的預製");
        m_find_sprite = GUILayout.TextArea(m_find_sprite);
        if (GUILayout.Button("查找") && !string.IsNullOrEmpty(m_find_sprite))
        {
            Debug.Log("開始查找.");
            loopCount = 0;
            results.Clear();
            FindSprite(m_find_sprite);
        }

        //---------------------------------------------------
        GUILayout.Label("\n查找所有帶此圖片的圖集");
        m_find_atlas_sprite = GUILayout.TextArea(m_find_atlas_sprite);
        if (GUILayout.Button("查找") && !string.IsNullOrEmpty(m_find_atlas_sprite))
        {
            Debug.Log("開始查找.");
            loopCount = 0;
            results.Clear();
            FindAtlasSprite(m_find_atlas_sprite);
        }
    }



    void FindScript()
    {
        List<string> prefabs_names = get_res_all_ui();

        if (scriptObj != null)
        {
            for (int i = 0; i < prefabs_names.Count; i++)
            {
                loopCount++;

                string[] str1 = AssetDatabase.GetAssetPathsFromAssetBundle(prefabs_names[i]);
                if (str1.Length < 1)
                {
                    Debug.Log("bundle no asset: " + prefabs_names[i]);
                    continue;
                }
                GameObject go = AssetDatabase.LoadAssetAtPath(str1[0], typeof(System.Object)) as GameObject;
                if (go != null)
                {
                    var thetype = scriptObj.GetClass();
                    Component[] co = go.GetComponentsInChildren(thetype, true);
                    foreach (var _child in co)
                    {
                        Debug.Log("<color=darkblue>Find it: " + go.name + "--->>" + _child.name + "</color>");

                        results.Add(_child.transform);
                    }
                }
            }
        }
        if (results.Count <= 0)
        {
            Debug.LogError("Oops: Cant find that you want !");
        }
    }

    void FindSprite(string sprite_name)
    {
        List<string> prefabs_names = get_res_all_ui();

        for (int i = 0; i < prefabs_names.Count; i++)
        {
            loopCount++;

            string[] str1 = AssetDatabase.GetAssetPathsFromAssetBundle(prefabs_names[i]);
            if (str1.Length < 1)
            {
                Debug.Log("bundle no asset: " + prefabs_names[i]);
                continue;
            }
            GameObject go = AssetDatabase.LoadAssetAtPath(str1[0], typeof(System.Object)) as GameObject;
            if (go != null)
            {
                UISprite[] co = go.GetComponentsInChildren<UISprite>(true);
                foreach (UISprite _child in co)
                {
                    if (_child.spriteName == sprite_name)
                    {
                        Debug.Log("<color=darkblue>Find it: " + go.name + "--->>" + _child.name + "</color>");

                        results.Add(_child.transform);
                    }
                }
            }
        }
        if (results.Count <= 0)
        {
            Debug.LogError("Oops: Cant find that you want !");
        }
    }

    void FindAtlasSprite(string _name)
    {
        string path = "Assets/atlas/";
        List<string> prefabs_names = new List<string>();
        if (Directory.Exists(path))
        {
            DirectoryInfo di = new DirectoryInfo(path);
            FileInfo[] files = di.GetFiles("*.prefab", SearchOption.AllDirectories);
            for (int i = 0; i < files.Length; i++)
            {
                string ab_name = "atlas/";
                if (files[i].Directory.Name != "atlas")
                {
                    ab_name += files[i].Directory.Name.ToLower() + "/";
                }
                prefabs_names.Add(ab_name + files[i].Name.Split('.')[0].ToLower());
            }
        }

        for (int i = 0; i < prefabs_names.Count; i++)
        {
            loopCount++;

            string[] str1 = AssetDatabase.GetAssetPathsFromAssetBundle(prefabs_names[i]);
            if (str1.Length < 1)
            {
                Debug.Log("bundle no asset: " + prefabs_names[i]);
                continue;
            }
            GameObject go = AssetDatabase.LoadAssetAtPath(str1[0], typeof(System.Object)) as GameObject;
            if (go != null)
            {
                UIAtlas[] co = go.GetComponentsInChildren<UIAtlas>();
                foreach (UIAtlas _child in co)
                {
                    for (int j = 0; j < _child.spriteList.Count; j++)
                    {
                        if (_child.spriteList[j].name == _name)
                        {
                            Debug.Log("<color=darkblue>Find it: " + go.name + "--->>" + _child.name + "</color>");

                            results.Add(_child.transform);
                        }
                    }
                }
            }
        }
        if (results.Count <= 0)
        {
            Debug.LogError("Oops: Cant find that you want !");
        }
    }

    List<string> get_res_all_ui()
    {
        List<string> prefabs_names = new List<string>();
        //獲取指定路徑下面的所有資源文件
        if (Directory.Exists(fullPath))
        {
            DirectoryInfo direction = new DirectoryInfo(fullPath);
            FileInfo[] files = direction.GetFiles("*.prefab", SearchOption.AllDirectories);
            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].Name.EndsWith(".prefab"))
                {
                    string ab_name = "cctv/";
                    if (files[i].Directory.Name != "cctv")
                    {
                        ab_name += files[i].Directory.Name + "/";
                    }
                    prefabs_names.Add(ab_name + files[i].Name.Split('.')[0]);
                }
            }
        }
        return prefabs_names;
    }
    
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章