unity里创建Lua脚本

本文介绍如何在Unity中通过C#脚本实现Lua脚本文件的自动生成。包括Lua模板文件设置、C#脚本编写及菜单项集成等步骤。

1 . 在Project界面创建文件夹  Editor/Lua/Template/lua.lua  注:最后的文件lua.lua可以先创建一个C#然后改后缀,lua文件里      可以随便写一些默认的值,我写的为“ print("#NAME#") ”。

2 . 创建C#脚本

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

public class CreateLua {
    [MenuItem("Assets/Create/Lua Sctipt",false,80)]
    public static void CreatNewLua() {
        ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<MyDoCreateScriptAsset>(),
            GetSelectedPathOrFallback() + "/New Lua.lua", null, "Assets/Editor/Lua/Template/lua.lua");
    }

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

3 . 保存,就可以了。注:我把这个C#脚本放在了文件夹Lua层级下,比较直观的知道这是创建lua用的。


转载自雨松:http://www.xuanyusong.com/archives/3732

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值