slua学习记录(一)

1.导入插件后  Slua/LuaObject文件夹下的文件全部为生成文件,生成方式为菜单中Slua -> All -> Make(每次Make之前最好先Clear一次)
2.unity - lua交互过程中的文件有:unity C#脚本(自写),LuaObject文件夹下的Lua_C#文件名的脚本(生成),对应的lua脚本(自写)
3.若想在lua中调用C#类,需在C#类中加入[CustomLuaClass]或[CustomLuaClassAttribute]属性
如:
[CustomLuaClass]
public class Deleg : MonoBehaviour
4.lua与C#互调并简单交互
如:只需建立一个新场景在场景中添加一个Button(UGUI),随便给一个游戏对象绑定LzdTest脚本即可运行
(C#)

using UnityEngine;
using System.Collections;
using SLua;
using System;
using LuaInterface;

[CustomLuaClass]
public class LzdTest : MonoBehaviour {
	
	//this is a delegate
	public delegate void LzdTestDelegate(string path, GameObject g);
	static public LzdTestDelegate lzd;

	
	LuaSvr l;
	LuaTable self;
	LuaFunction update;
	void Start()
	{
		l = new LuaSvr();
		l.init(null,()=>{
			self = (LuaTable)l.start("lzdtest");
			update = (LuaFunction)self["update"];
			//C# call lua
			string str = (string)l.luaState.getFunction ("lzdFunc").call ("hello world");
			Debug.Log (str);
		});

	}

	void Update () {
		//call lua “update” function in Update
		if(update!=null) update.call(self);
	}


	static public void callD()
	{
		//call delegate function
		if (lzd != null)
			lzd("GameObject", new GameObject("SimpleDelegate"));
		Debug.Log ("callD");
	}

	//lua call C#
	public void luaCallCS(string wtf)
	{
		Debug.Log (wtf);
	}
}

 

 

 

(Lua)

 

import "UnityEngine"
if not UnityEngine.GameObject then
	error("Click Make/All to generate lua wrap file")
end

local class={}

function main()
	print("run lua main function")
	local cs = GameObject.Find("Main Camera")
	
	--If your class does not inheritance MonoBehaviour,you can write like this : 
	--local h=LzdTest()
	--h.luaCallCS("wtf")
	local te = cs:GetComponent("LzdTest")
	te:luaCallCS("wtf")


	local g;
	--test delegate
	LzdTest.lzd=function(path,go)
	g = go
		print(path,go.name)
	end
	LzdTest.callD()

	-- test gameobject
	print(g.name)
	print(cs.name)
	g.transform.parent = cs.transform
	g:AddComponent(UnityEngine.Rigidbody)
	g:AddComponent(UnityEngine.BoxCollider)
	local c=g:AddComponent(UnityEngine.MeshRenderer)
	c.probeAnchor = cs.transform

	-- test UI
	local obj = GameObject.Find("Canvas/Button")
	local btn = obj:GetComponent("Button")
	local num = 0
	btn.onClick:AddListener(function()
		num = num+1
		print(" click btn ,","num = ",num)
	end)

	--if you want to use update function,you need return class 
	return class
end

function lzdFunc(a)
	HelloWorld.nullf(1)
	HelloWorld.nullf()
	print("run this function")
	local name = " lzd"
	a = a..name
	return a
end

-- use update on lua
function class:update()
	print(Time.deltaTime)
end

 

 

 

 

 

你可能感兴趣的:(unity)