Enumerable.Cast(IEnumerable) Method :
Casts the elements of an IEnumerable to the specified type.
将一个IEnumerable的元素转换为一个具体的类型。
实现Unity中的Unity生命周期
1.获取Lua的表
2.获取表中的Update方法
3.使用强制类型转换将LuaFunction转换成一个委托方法,此委托方法可以传入LuaTable自身
4.在C#中调用转换成委托的方法并传入LuaTable
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using UnityEngine;
using SLua;
using System.IO;
using System;
public class OpenLuaFile : MonoBehaviour {
private LuaSvr lua_svr;
private LuaTable self;
private LuaFunction update;
[CustomLuaClass]
public delegate void UpdateDelegate(object self);
UpdateDelegate ud;
void Start () {
lua_svr = new LuaSvr();
lua_svr.init(null, InitComplete,LuaSvrFlag.LSF_EXTLIB);
}
private void InitComplete()
{
//自定义Lua文件
LuaState.main.loaderDelegate += LuaLoader;
self = (LuaTable)lua_svr.start("HelloLua");
update = (LuaFunction)self["Update"];
ud = update.cast<UpdateDelegate>();
}
private void Update()
{
if (ud != null)
{
ud(self);
}
}
[DoNotToLua]
private byte[] LuaLoader(string fn, ref string absoluteFn)
{
string newFn = fn.Replace(".", "/");
string path = Application.dataPath + "/Scripts/Lua/" + newFn + ".lua";
byte[] data = null;
if (File.Exists(path))
{
data = File.ReadAllBytes(path);
}
else
{
TextAsset txt = Resources.Load<TextAsset>(newFn);
}
return data;
}
}
Lua中的表中定义的Update方法
function main()
maxItemCount = 40;
scrollRect = GameObject.Find("Canvas/Backpack"):GetComponent(UI.ScrollRect);
content = scrollRect.content;
contentGridLayoutGroup = content:GetComponent(UI.GridLayoutGroup);
columnCount = math.floor((content.rect.width - contentGridLayoutGroup.spacing.x)/contentGridLayoutGroup.cellSize.x);
if columnCount ~= 0 then
rowCount = math.ceil( content.childCount/columnCount );
curBottomIndex = (rowCount - 1)*columnCount;
initializedBottomIndex = curBottomIndex;
end
oneBlockHeight = contentGridLayoutGroup.cellSize.y + contentGridLayoutGroup.spacing.y;
local contentSizeDeltaY = math.floor( oneBlockHeight * (math.ceil(maxItemCount / columnCount))) ;
content.sizeDelta = UnityEngine.Vector2(content.sizeDelta.x,contentSizeDeltaY);
for i=1,maxItemCount do
table.insert(itemIDs,i);
end
scrollRect.onValueChanged:AddListener(ListenerMethod);
FreshBackpack();
return class;
end
function class : Update()
if UnityEngine.Input.GetKeyDown(KeyCode.Space) then
JumpToTargetID(12);
end
if UnityEngine.Input.GetKeyDown(KeyCode.A) then
if #itemIDs < maxItemCount then
table.insert( itemIDs,math.random(0,100) );
FreshBackpack();
else
print("BP Full!");
end
end
end
网友评论