0

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

    2023.06.23 | admin | 104次围观

    1、unity的脚本模板

    新版本unity中的C#脚本有三类,第一类是我们平时开发用的C# Script;第二类是Testing,用来做单元测试;第三类是Playables,用作TimeLine中管理时间线上每一帧的动画、声音等。我们点击创建脚本时,会自动生成unity内置的一套模板:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class NewBehaviourScript : MonoBehaviour {
     // Use this for initialization
     void Start () {
      
     }
     
     // Update is called once per frame
     void Update () {
      
     }
    }

    如果我们开发时使用的框架有明显的一套基础模板, 那为项目框架定制一套模板会很有意义,这样可以为我们省去编写重复代码的时间。这里介绍两种方法。

    2、修改默认脚本模板

    打开unity安装目录,比如D:\unity2018\Editor\Data\Resources\ScriptTemplatescs准心脚本下载到那个文件夹,unity内置的模板脚本都在这里,那么可以直接修改这里的cs文件,比如我们将81-C# Script-NewBehaviourScript.cs.txt文件修改为如下,那下次创建C# Script时模板就会变成这样:

    ////////////////////////////////////////////////////////////////////
    //       _ooOoo_        //
    //       o8888888o        //
    //       88" . "88        //
    //       (| ^_^ |)        //
    //       O\ = /O        //
    //      ____/`---'\____       //
    //     .' \\|  |// `.       //
    //     / \\||| : |||// \      //
    //     / _||||| -:- |||||- \      //
    //     | | \\\ - /// | |      //
    //     | \_| ''\---/'' | |      //
    //     \ .-\__ `-` ___/-. /      //
    //    ___`. .' /--.--\ `. . ___      //
    //    ."" '< `.___\_<|>_/___.' >'"".     //
    //   | | : `- \`.;`\ _ /`;.`/ - ` : | |     //
    //   \ \ `-. \_ __\ /__ _/ .-` / /     //
    //  ========`-.____`-.___\_____/___.-`____.-'========   //
    //       `=---='        //
    //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  //
    //   佛祖保佑  永不宕机  永无BUG     //
    ////////////////////////////////////////////////////////////////////
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class #SCRIPTNAME# : MonoBehaviour {
     // Use this for initialization
     void Start () {
      #NOTRIM#
     }
     
     // Update is called once per frame
     void Update () {
      #NOTRIM#
     }
    }

    3、拓展脚本模板

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

    首先cs准心脚本下载到那个文件夹,先创建一个文本文件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来监听回调,最终实现输入脚本名字后自动创建相应的脚本模板。

    代码如下,将这个脚本放入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(),
        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));
      }
    }

    然后,在project中,点击创建C# FrameScript,输入脚本名字,对应的脚本就已经创建好了

    4、总结

    上面介绍了两种方案,第一种适合玩玩,第二种方法显然逼格高一些,为不同的项目和框架定制一套脚本模板,可以让我们少写一些重复代码。按照上面介绍的方法,我们同样可以修改和拓展Testing、Playables的脚本模板,甚至shader,我们也可以定制模板。

    好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对鸿网互联的支持。

    版权声明

    本文仅代表作者观点。
    本文系作者授权发表,未经许可,不得转载。

    标签: unityc#
    发表评论