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(), 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));
    }
}

你可能感兴趣的:(Unity)