自定义脚本模板
Posted llstart-new0201
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义脚本模板相关的知识,希望对你有一定的参考价值。
两种方法:
1)在unity安装目录下的EditorDataResourcesScriptTemplates81-C# Script-NewBehaviourScript.cs.txt即为脚本模板,直接修改成自己需要的即可
2)第二种方法来自宣雨松的《unity3D游戏开发的》第二版,即通过扩展编辑器实现:
第一步:unity工程中新建Editor目录,并放入如下所示脚本:
using System.IO; using System.Text; using System.Text.RegularExpressions; using UnityEditor; using UnityEditor.ProjectWindowCallback; using UnityEngine; public class CustomizedScriptTemplate : MonoBehaviour { //脚本模板所目录 private const string MY_SCRIPT_DEFAULT = "Assets/Editor/ScriptTemplates/C# Script-NewBehaviourScript.cs.txt"; [MenuItem("Assets/Create/C# CustomizedScript", false, 80)] public static void CreatMyScript() { string locationPath = GetSelectedPathOrFallback(); ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<MyDoCreateScriptAsset>(), locationPath + "/NewBehaviourScript.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) { UnityEngine.Object o = CreateScriptAssetFromTemplate(pathName, resourceFile); ProjectWindowUtil.ShowCreatedAsset(o); } 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, "#NAME#", fileNameWithoutExtension); bool encoderShouldEmitUTF8Identifier = true; 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); return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object)); } }
第二步:在第一步的Editor下新建目录ScriptTemplate目录,并放入脚本模板,脚本模板如下所示:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class #NAME# : MonoBehaviour { void MyFunction() { } }
目录结构如下所示:
然后就可以右键Create创建自定义脚本模板了:
以上是关于自定义脚本模板的主要内容,如果未能解决你的问题,请参考以下文章