在学习Xlua时,这个工具提供了一个简单而强大的方式来快速生成基于模板的Lua脚本,有助于提高开发效率和保持代码的一致性。
1.xlua框架导入
在GitHub上搜索xlua,找到腾讯的xlua项目,下载项目的压缩包。然后将压缩包里的Plugins和XLua这两个文件夹导入Unity的Assets目录下,如下图所示:
2.XLua菜单选项
将这两个文件夹复制到Unity的Assets目录下后稍等一会儿,就会发现在菜单栏中Windows菜单选项左侧出现了XLua菜单选项,没有报错的话说明成功导入。如下图所示:
3.实现基于模板的Lua脚本的工具
3-1.首先在Assets目录下创建Editor目录,然后在Editor目录下创建CreateLuaScript目录,最后在CreateLuaScript目录下创建CreateLuaScript.cs脚本
3-2 CreateLuaScript.cs如下:
点击查看代码
```
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
/// <summary>
/// Lua脚本创建工具,支持从模板创建Lua脚本。
/// </summary>
public class CreateLuaScript : EditorWindow
{
private string scriptName = ""; // 脚本名称
private int selectedTemplateIndex = 0; // 选中的模板索引
private string[] templateOptions = { "Basic Template", "Advanced Template" }; // 模板选项
private string path; // 保存路径
private bool isFocused = false; // 是否已聚焦到输入框
/// <summary>
/// 初始化窗口
/// </summary>
[MenuItem("Assets/Create/Lua Script", false, 80)]
private static void Init()
{
var window = GetWindowWithRect<CreateLuaScript>(new Rect(0, 0, 350, 125), true, "Lua Script Creator");
window.Setup();
}
/// <summary>
/// 设置初始状态
/// </summary>
private void Setup()
{
path = GetSelectedPathOrFallback();
isFocused = false;
}
/// <summary>
/// 绘制用户界面
/// </summary>
void OnGUI()
{
EditorGUILayout.LabelField("Lua Script Name:", EditorStyles.boldLabel);
GUI.SetNextControlName("ScriptNameTextField");
scriptName = EditorGUILayout.TextField(scriptName).Trim();
EditorGUILayout.LabelField("Select Template:", EditorStyles.boldLabel);
selectedTemplateIndex = EditorGUILayout.Popup(selectedTemplateIndex, templateOptions);
if (!isFocused)
{
EditorGUI.FocusTextInControl("ScriptNameTextField");
isFocused = true;
}
Event e = Event.current;
bool enterPressed = e.type == EventType.KeyDown && (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter);
if (GUILayout.Button("Create") || enterPressed)
{
if (ValidateScriptName(scriptName))
{
CreateScriptFromTemplate();
Close();
}
}
}
/// <summary>
/// 验证脚本名称
/// </summary>
/// <param name="scriptName">脚本名称</param>
/// <returns>是否有效</returns>
private bool ValidateScriptName(string scriptName)
{
if (string.IsNullOrWhiteSpace(scriptName))
{
EditorUtility.DisplayDialog("Error", "Script name cannot be empty.", "OK");
return false;
}
string fullPath = $"{path}{scriptName}.lua.txt";
if (File.Exists(fullPath))
{
EditorUtility.DisplayDialog("Error", "A script with this name already exists.", "OK");
return false;
}
return true;
}
/// <summary>
/// 根据模板创建Lua脚本
/// </summary>
private void CreateScriptFromTemplate()
{
string templateContent = GetTemplateContentByIndex(selectedTemplateIndex);
string fullPath = $"{path}{scriptName}.lua.txt";
File.WriteAllText(fullPath, templateContent);
AssetDatabase.Refresh();
Debug.Log($"Lua script created: {fullPath}");
EditorUtility.DisplayDialog("Success", $"Lua script \"{scriptName}.lua.txt\" created successfully.", "OK");
}
/// <summary>
/// 获取选中模板的内容
/// </summary>
/// <param name="index">模板索引</param>
/// <returns>模板内容字符串</returns>
private string GetTemplateContentByIndex(int index)
{
string filePath = "";
switch (index)
{
case 0:
filePath = "Assets/Editor/CreateLuaScript/LuaTemplates/BasicTemplate.lua.txt";
break;
case 1:
filePath = "Assets/Editor/CreateLuaScript/LuaTemplates/AdvancedTemplate.lua.txt";
break;
default:
filePath = "Assets/Editor/CreateLuaScript/LuaTemplates/DefaultTemplate.lua.txt";
break;
}
if (!File.Exists(filePath))
{
Debug.LogError("Template file not found: " + filePath);
return "-- Template file not found";
}
try
{
string content = File.ReadAllText(filePath);
return content;
}
catch (Exception ex)
{
Debug.LogError("Failed to read template file: " + ex.Message);
return "-- Failed to read template file";
}
}
/// <summary>
/// 获取当前选中的路径或回退到默认路径。
/// </summary>
/// <returns>路径字符串</returns>
private static string GetSelectedPathOrFallback()
{
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
if (!string.IsNullOrEmpty(path) && File.Exists(path))
{
return Path.GetDirectoryName(path) + "/";
}
return "Assets/";
}
}
```
</details>
3.3 在CreateLuaScript目录下创建LuaTemplates目录,在这个创建的目录下创建AdvancedTemplate.lua.txt,BasicTemplate.lua.txt,DefaultTemplate.lua.txt三个文件。如下图所示:
3.4 在三个Template下各自print自身
3.5 测试,鼠标右键之后,如下图所示:
3.6 点击Lua Scripts
3.7 重命名并选择lua脚本模板
3.8 点击Create,点击ok,lua脚本根据自定义的模板创建成功