90 lines
2.2 KiB
C#
90 lines
2.2 KiB
C#
|
|
|
|
using System.Threading;
|
|
using UnityEngine;
|
|
using XLua;
|
|
using System.IO;
|
|
|
|
class LuaServer : MonoBehaviour
|
|
{
|
|
public static LuaEnv m_LuaEnv = new LuaEnv();
|
|
|
|
private Thread _thread;
|
|
private bool _isThreadRunning;
|
|
private string _result;
|
|
private float _timeBegin = 0;
|
|
|
|
void Start()
|
|
{
|
|
//初始化
|
|
m_LuaEnv.AddLoader((ref string path) =>
|
|
{//加载器 默认先从基础文件找,然后再去当前库找
|
|
string fixedPath = path.Replace('.', '/');
|
|
//Debug.Log($"Base Loader : {fixedPath}");
|
|
|
|
#if UNITY_EDITOR
|
|
byte[] content = null;
|
|
//编辑器查找底层lua本地文件
|
|
if (File.Exists($"assets/lua/{fixedPath}.lua"))
|
|
{
|
|
content = System.IO.File.ReadAllBytes($"assets/lua/{fixedPath}.lua");
|
|
if (content != null)
|
|
{
|
|
return content;
|
|
}
|
|
}
|
|
string luaPath = $"../Lua/{fixedPath}.lua";
|
|
if (File.Exists(luaPath))
|
|
{
|
|
content = System.IO.File.ReadAllBytes(luaPath);
|
|
if (content != null)
|
|
{
|
|
return content;
|
|
}
|
|
}
|
|
|
|
#endif
|
|
return null;
|
|
});
|
|
m_LuaEnv.DoString("require'server/xwserver'");
|
|
|
|
// 启动子线程
|
|
_thread = new Thread(Run);
|
|
_isThreadRunning = true;
|
|
_thread.Start();
|
|
|
|
_timeBegin = Time.realtimeSinceStartup;
|
|
}
|
|
void Update()
|
|
{
|
|
// 在主线程中处理子线程的结果
|
|
if (!_isThreadRunning && _result != null)
|
|
{
|
|
Debug.Log("Result from thread: " + _result);
|
|
_result = null; // 清除结果,避免重复处理
|
|
}
|
|
}
|
|
|
|
void Run()
|
|
{
|
|
// 模拟耗时操作
|
|
while (_thread != null)
|
|
{
|
|
Thread.Sleep(66);
|
|
if (Time.realtimeSinceStartup - _timeBegin > 60)//60秒退出
|
|
{
|
|
_result = "Work completed!";
|
|
_isThreadRunning = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
void OnDestroy()
|
|
{
|
|
// 确保在销毁时停止子线程
|
|
if (_thread != null && _thread.IsAlive)
|
|
{
|
|
_thread.Abort();
|
|
}
|
|
}
|
|
} |