Unity拓展脚本模板

最近在看Unity3d游戏开发第二版(作者雨松momo)这本书,记录下学习的东西。
1.Unity 文件夹下保存着一份脚本模板 在目录:Unity\Editor\Data\Resources\ScriptTemplates下。如果需要新的,可以在该目录下仿照格式重新添加一套新的模板格式。
2.为了方便版本管理,可以自己写一套新加模板的方法,代码如下:

using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.ProjectWindowCallback;
using System.Text.RegularExpressions;
using System.Text;
public class CreateScriptTools
{
    private const string MY_SCRIPT_DEFAULT = "Assets/Editor/ScriptsTemplates/C# Script-NewBehaviourScript.cs.txt";
    [MenuItem("Assets/Create/C# MyScripts", false, 100)]
    public static void CreateScripts()
    {
        string localPath = GetSelectedPathOrFallBack();
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<MyDoCreateScriptAsset>(), localPath + "/MyNewBehaviourScript.cs", null, MY_SCRIPT_DEFAULT);
    }
    public static string GetSelectedPathOrFallBack()
    {
        string path = "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;
    }
}
class MyDoCreateScriptAsset : EndNameEditAction
{
    public override void Action(int instanceId, string pathName, string resourceFile)
    {
        Debug.Log("EndNameAction");
        UnityEngine.Object o = CreateScriptsFromTemplate(pathName, resourceFile);
        ProjectWindowUtil.ShowCreatedAsset(o);
    }
    internal static UnityEngine.Object CreateScriptsFromTemplate(string pathName, string resourceFolder)
    {
        string fullPath = Path.GetFullPath(pathName);
        StreamReader streamReader = new StreamReader(resourceFolder);
        string text = streamReader.ReadToEnd();
        streamReader.Close();
        string fileNameWithOutExtension = Path.GetFileNameWithoutExtension(pathName);
        text = Regex.Replace(text, "#NAME#", fileNameWithOutExtension);
        bool encoderShouldEmitUTF8Identifer = true;
        bool throwOnInvalidBytes = false;
        UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifer, throwOnInvalidBytes);
        bool append = false;
        StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
        streamWriter.Write(text);
        streamWriter.Close();
        AssetDatabase.ImportAsset(pathName);
        return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值