1. 程式人生 > >Unity中使用 slua --- 呼叫c#方法

Unity中使用 slua --- 呼叫c#方法

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