Unity自定义Script模板

Unity默认创建的脚本,继承MonoBehaviour,且自带Start()和OnUpdate()方法,大部分时候都是不需要OnUpdate()方法的,有时候也不需要继承MonoBehaviour,所以来自定义一个模板,省得手动删代码。

首先找到Unity中代码模板的位置:

Unity\Hub\Editor\2019.4.9f1\Editor\Data\Resources\ScriptTemplates

这里面就是Unity创建脚本时的模板了。

新建一个文件,命名为:NewC#Script__NewScript-NormalScript.cs.txt,其中NewC#Script是菜单栏上显示的名字,NewScript是子菜单栏上显示的名字,NormalScript是创建的脚本的默认名字,如下所示。

这里创建了两个模板,一个是普通脚本不继承MonoBehaviour的,命名如上。还有一个模板是继承MonoBehaviour的,命名:NewC#Script__NewBehaviourScript-BehaviourScript.cs.txt 

模板脚本代码:

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

public class #SCRIPTNAME# : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        #NOTRIM#
    }
}
public class #SCRIPTNAME#
{
    
}

在创建脚本的时候还可以加上文件头信息:如加上脚本的创建者,创建时间等。下面就是模板

//文件名(File Name):    #SCRIPTNAME##FILEEXTENSION#
//
//作者(Author):         #AUTHORNAME#
//
//创建时间(CreateTime): #CREATIONDATE#

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

public class #SCRIPTNAME# : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        #NOTRIM#
    }
}

然后在Editor文件夹下创建一个Editor脚本用来解析上面的模板:

using UnityEngine;
using UnityEditor;

public class NewScriptTemplate : UnityEditor.AssetModificationProcessor
{
    public static void OnWillCreateAsset(string path)
    {
        path = path.Replace(".meta", "");
        int index = path.LastIndexOf(".");
        string file = path.Substring(index);
        if (file != ".cs" && file != ".js" && file != ".boo") return;
        string fileExtension = file;

        index = Application.dataPath.LastIndexOf("Assets");
        path = Application.dataPath.Substring(0, index) + path;
        file = System.IO.File.ReadAllText(path);

        file = file.Replace("#SCRIPTNAME#", PlayerSettings.productName);
        file = file.Replace("#FILEEXTENSION#", fileExtension);
        file = file.Replace("#AUTHORNAME#", "张三");
        file = file.Replace("#CREATIONDATE#", System.DateTime.Now.ToString("d"));

        System.IO.File.WriteAllText(path, file);
        AssetDatabase.Refresh();
    }
}

创建出来的脚本就是下面的样子了

//文件名(File Name):    BehaviourScript.cs
//
//作者(Author):         张三
//
//创建时间(CreateTime): 2021/11/25

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

public class BehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值