Unity Editor - Preview Lua files
By default, the Inspector window of the Unity editor cannot directly display Lua file details.
Directly modify the Inspector display
Lua files are recognized as DefaultAsset by default. We can preview Lua files by overriding the Inspector panel of DefaultAsset.
using System.IO;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(DefaultAsset))]
public class LuaInspector : UnityEditor.Editor
{
GUIStyle textStyle;
const int MaxLength = 5000;
string detail;
public override void OnInspectorGUI()
{
if (textStyle is null)
{
textStyle = new GUIStyle();
textStyle.normal.textColor = Color.white;
}
string assetPath = AssetDatabase.GetAssetPath(target);
if (!assetPath.EndsWith(".lua"))
return;
if (string.IsNullOrEmpty(detail))
{
detail = File.ReadAllText(assetPath);
if (detail.Length > MaxLength)
detail = detail.Substring(0, MaxLength) + "...\n\n<...etc...>";
}
GUILayout.Box(detail, textStyle);
}
}
Convert to TextAsset for display
After reading the file content, generate a new TextAsset and then use the newly generated TextAsset as the main object
using System.IO;
using UnityEditor.AssetImporters;
using UnityEngine;
[ScriptedImporter(1, ".lua")]
public class LuaImporter : ScriptedImporter
{
string luaTxt;
public override void OnImportAsset(AssetImportContext ctx)
{
if (string.IsNullOrEmpty(luaTxt))
luaTxt = File.ReadAllText(ctx.assetPath);
var display = new TextAsset(luaTxt);
ctx.AddObjectToAsset("Lua Script", display);
ctx.SetMainObject(display);
}
}
reference
https://docs.unity.cn/cn/current/ScriptReference/AssetImporters.ScriptedImporter.html