unity学习教程之定制脚本模板示例代码

2020-01-05 10:13:30刘景俊

3、拓展脚本模板

上面讲的第一种方法直接修改了unity的默认配置,这并不适应于所有项目,这里第二种方法会更有效,可以针对不同的项目和框架创建合适的脚本模板。

首先,先创建一个文本文件MyTemplateScript.cs.txt作为脚本模板,并将其放入unity project的Editor文件夹下,模板代码为:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyNewBehaviourScript : MonoBase {

 //添加事件监听
 protected override void AddMsgListener()
 {

 }
 
 //处理消息
 protected override void HandleMsg(MsgBase msg)
 {
  switch (msg.id)
  {
   default:
    break;
  }
 }

}

我们使用时,需要在Project视图中右击->Create->C# FrameScript 创建脚本模板,因此首先要创建路径为Assets/Create/C# FrameScript的MenuItem,点击创建脚本后,需要修改脚本名字,因此需要在拓展编辑器脚本中继承EndNameEditAction来监听回调,最终实现输入脚本名字后自动创建相应的脚本模板。

unity,脚本,模板,代码

代码如下,将这个脚本放入Editor文件夹中:


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

public class CreateTemplateScript {

  //脚本模板路径
  private const string TemplateScriptPath = "Assets/Editor/MyTemplateScript.cs.txt";

  //菜单项
  [MenuItem("Assets/Create/C# FrameScript", false, 1)]
  static void CreateScript()
  {
    string path = "Assets";
    foreach (UnityEngine.Object item in Selection.GetFiltered(typeof(UnityEngine.Object),SelectionMode.Assets))
    {
      path = AssetDatabase.GetAssetPath(item);
      if (!string.IsNullOrEmpty(path) && File.Exists(path))
      {
        path = Path.GetDirectoryName(path);
        break;
      }
    }
    ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<CreateScriptAsset>(),
    path + "/MyNewBehaviourScript.cs",
    null, TemplateScriptPath);

  }
  
}


class CreateScriptAsset : EndNameEditAction
{
  public override void Action(int instanceId, string newScriptPath, string templatePath)
  {
    UnityEngine.Object obj= CreateTemplateScriptAsset(newScriptPath, templatePath);
    ProjectWindowUtil.ShowCreatedAsset(obj);
  }

  public static UnityEngine.Object CreateTemplateScriptAsset(string newScriptPath, string templatePath)
  {
    string fullPath = Path.GetFullPath(newScriptPath);
    StreamReader streamReader = new StreamReader(templatePath);
    string text = streamReader.ReadToEnd();
    streamReader.Close();
    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(newScriptPath);
    //替换模板的文件名
    text = Regex.Replace(text, "MyTemplateScript", 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(newScriptPath);
    return AssetDatabase.LoadAssetAtPath(newScriptPath, typeof(UnityEngine.Object));
  }

}