当前位置: 首页 > 工具软件 > Monster > 使用案例 >

自动制作Monster预制体

谭彦
2023-12-01
//=====================================================
// - 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));
    }
}

 

 类似资料: