slua下载地址:https://github.com/pangweiwei/slua
1.在使用slua 每次make 最后都执行一次claer
2.在你需要调用的c#类中添加 [CustomLuaClass] 特性
绑定在Camera的脚本
using UnityEngine;
using System.Collections;
using SLua;
[CustomLuaClass]
public class ChatRoom : MonoBehaviour {
//在别的项目实现的Tcp Socket
private Server sever = null;
// Use this for initialization
void Start () {
sever = new Server("127.0.0.1", 6523);
}
// Update is called once per frame
void Update () {
}
/// <summary>
/// 连接服务器
/// </summary>
//slua 要调用的方法
public void Connect()
{
sever.Connect();
}
//slua要调用的方法
public void OnClickMsgSendButEvent(string text)
{
string[] setext = { text };
sever.SendMessage(sever.BuildDataPackage(10011, setext));
}
}
绑定Gameobject的脚本(可以随便创建一个绑定)
using UnityEngine;
using System.Collections;
using SLua;
using System.IO;
public class ChatRoomManager : MonoBehaviour {
LuaSvr lua_Svr;
LuaTable self;
LuaFunction start;
private void Awake()
{
lua_Svr = new LuaSvr();
LuaState.loaderDelegate = ((string fn) => {
string path = Directory.GetCurrentDirectory() + "/Assets/Resources/" + fn;
Debug.Log(path);
return File.ReadAllBytes(path);
});
lua_Svr.init(null, () =>
{
self = (LuaTable)lua_Svr.start("ChatRoomClient.lua");
});
}
// Use this for initialization
void Start () {
DontDestroyOnLoad(gameObject);
}
// Update is called once per frame
void Update () {
}
}
lua文件
import "UnityEngine"
if not UnityEngine.GameObject then
error("Click Make/All to generate lua wrap file")
end
function main( ... )
-- body
print("Start ConnectServer");
local ca = GameObject.Find("Main Camera");
local cs = ca:GetComponent("ChatRoom");
cs:Connect();
print("Success Server");
local sendBut = GameObject.Find("Canvas/Send");
local btn = sendBut:GetComponent("Button")
if not sendBut then
error("sendBut is nil");
end
btn.onClick:AddListener(function ()
-- body
print("Button");
local msg = GameObject.Find("Canvas/Msg/Text");
local mtext = msg:GetComponent("Text");
cs:OnClickMsgSendButEvent(mtext.text);
local text1 = GameObject.Find("Canvas/Image/Text");
local textt = text1:GetComponent("Text");
textt.text = mtext;
end);
end