自動製作Monster預製體

//=====================================================
// - FileName:      AutoCreateMonster.cs
// - Author:       #AuthorName#
// - CreateTime:    #CreateTime#
// - Email:         #AuthorEmail#
// - Description:   
// -  (C) Copyright 2019, webeye,Inc.
// -  All Rights Reserved.
//======================================================
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Qarth;
using UnityEditor;
using System.IO;
using System.Text;
using Spine.Unity;
using Spine;
using UnityEditor.Animations;
using UnityEditor.SceneManagement;


namespace GameWish.Game
{
    public class AutoCreateMonster : EditorWindow
    {
        [MenuItem("Autumn/CreateMonster")]
        private static void AddUIPanel2AllPanelDic()
        {
            Rect rect = new Rect(0, 0, 500, 550);
            AutoCreateMonster window = (AutoCreateMonster)EditorWindow.GetWindowWithRect(typeof(AutoCreateMonster), rect, true, "增加Monster");
            window.Show();
        }
        string monsterName;
        SkeletonDataAsset m_SkeletonDataAsset;
        AnimatorController animatorController;
        string m_TargetPath = "Assets/Res/FolderMode/Prefab/Monster/Monster_{0}.prefab";

        private void OnGUI()
        {
            monsterName = EditorGUILayout.TextField("請輸入怪物名稱", monsterName);
            m_SkeletonDataAsset = EditorGUILayout.ObjectField("選擇SkeletonDataAsset", m_SkeletonDataAsset, typeof(SkeletonDataAsset), true) as SkeletonDataAsset;
            animatorController = EditorGUILayout.ObjectField("選擇AnimatorController", animatorController, typeof(AnimatorController), true) as AnimatorController;
            if (GUILayout.Button("生成預製體", GUILayout.Width(200)))
            {
                GameObject go = PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath("Assets/Res/FolderMode/MonsterPrefab/Monster_Prefab.prefab", typeof(GameObject))) as GameObject;
                Transform monsterRoot = go.transform.GetChild(0);
                monsterRoot.GetComponent<SkeletonAnimator>().skeletonDataAsset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(m_SkeletonDataAsset), typeof(SkeletonDataAsset)) as SkeletonDataAsset;
                monsterRoot.GetComponent<Animator>().runtimeAnimatorController = animatorController;
                monsterRoot.GetComponent<Renderer>().sharedMaterial.shader = ShaderFinder.FindShader("Spine/Effect");
                monsterRoot.name = monsterName;
                if (go.transform.GetComponent<EnemyBase>() != null)
                {
                    DestroyImmediate(go.transform.GetComponent<EnemyBase>());
                }
                PanelScript.CreateMonsterScripts(monsterName);
                bool success;
                object tempPrefab = PrefabUtility.SaveAsPrefabAsset(go, string.Format(m_TargetPath, monsterName), out success);
                DestroyImmediate(go);
                if (success)
                {
                    this.ShowNotification(new GUIContent("生成預製體成功!"));
                    AssetDatabase.Refresh();
                    EditorSceneManager.MarkAllScenesDirty();
                }
            }
        }

    }
}

自動寫代碼模板:

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

public class PanelScript : EditorWindow
{
    [MenuItem("Assets/CreatePanelScripts", priority = 0)]
    private static void CreatePanelScript()
    {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
                    ScriptableObject.CreateInstance<CreatePanelScriptAsset>(),
                    GetSelectPathOrFallback() + "/New Panel.cs", null,
                    "Assets/Scripts/Editor/CreatePanel/panel.cs.txt");
    }

    public static void CreateMonsterScripts(string name)
    {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0,
                    ScriptableObject.CreateInstance<CreatePanelScriptAsset>(),
                    "Assets/Scripts/Game/Gameplay/Entity/Enemy" + "/Monster" + name + ".cs", null,
                    "Assets/Scripts/Editor/CreateMonster/Monster.cs.txt");
    }
    //取得要創建文件的路徑
    public static string GetSelectPathOrFallback()
    {
        string path = "Assets";
        //遍歷選中的資源以獲得路徑
        //Selection.GetFiltered是過濾選擇文件或文件夾下的物體,assets表示只返回選擇對象本身
        foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets))
        {
            path = AssetDatabase.GetAssetPath(obj);
            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                path = Path.GetDirectoryName(path);
                break;
            }
        }
        return path;
    }
}


//要創建模板文件必須繼承EndNameEditAction,重寫action方法
class CreatePanelScriptAsset : EndNameEditAction
{
    public override void Action(int instanceId, string pathName, string resourceFile)
    {
        //創建資源
        UnityEngine.Object obj = CreateScriptAssetFromTemplate(pathName, resourceFile);
        ProjectWindowUtil.ShowCreatedAsset(obj);//高亮顯示資源
    }

    internal static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
    {
        //獲取要創建資源的絕對路徑
        string fullPath = Path.GetFullPath(pathName);
        //讀取本地的模板文件
        StreamReader streamReader = new StreamReader(resourceFile);
        string text = streamReader.ReadToEnd();
        streamReader.Close();
        //獲取文件名,不含擴展名
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);

        //將模板類中的類名替換成你創建的文件名
        text = Regex.Replace(text, "#SCRIPTNAME#", fileNameWithoutExtension);
        bool encoderShouldEmitUTF8Identifier = true; //參數指定是否提供 Unicode 字節順序標記
        bool throwOnInvalidBytes = false;//是否在檢測到無效的編碼時引發異常
        UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
        bool append = false;
        //寫入文件
        StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
        streamWriter.Write(text);
        streamWriter.Close();
        //刷新資源管理器
        AssetDatabase.ImportAsset(pathName);
        AssetDatabase.Refresh();
        return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
    }
}

 

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