在lua调用Unity中的对象时,在其内部进行了大量的操作,十分消耗性能。
详情:用好Lua+Unity,让性能飞起来——Lua与C#交互篇_画个小圆儿的博客-CSDN博客
基于如此,实现了一个工具,使lua层代码只拿到Unity中对象的引用,在C#层使用列表记录对象的索引ID,当每次lua使用时进传入像应的ID调用相应的方法就好。示例代码如下:
C#:
public const int WIDGET_ID_BASE = 1000;
private WidgetInfo WidgetByID(int widgetID)
{
WidgetInfo widget;
int index = widgetID - LuaGameObjectHelper.WIDGET_ID_BASE - 1;
if (index >= 0 && index < Widgets.Length)
{
return Widgets[index];
}
return null;
}
public bool SetUILabel_Text(int widgetID, string text)
{
WidgetInfo widget = WidgetByID(widgetID);
if (widget != null && widget.label != null)
{
widget.label.text = text;
return true;
}
return false;
}
public bool SetMyUILabel_Text(int widgetID, string args0, params object[] args)
{
WidgetInfo widget = WidgetByID(widgetID);
//if (widget != null && widget.label != null && widget.label as MyUILabel != null)
//{
// MyUILabel myUILabel = widget.label as MyUILabel;
// myUILabel.SpliceLabel(args0, args);
// return true;
//}
return false;
}
public string GetUILabel_Text(int widgetID)
{
WidgetInfo widget = WidgetByID(widgetID);
if (widget != null && widget.label != null)
{
return widget.label.text;
}
return null;
}
public bool SetUILabel_Color(int widgetID, float r, float g, float b, float a)
{
WidgetInfo widget = WidgetByID(widgetID);
if (widget != null && widget.label != null)
{
widget.label.color = new Color(r, g, b, a);
return true;
}
return false;
}
public int GetUILabel_FontSize(int widgetID)
{
int fontsize = 18;
WidgetInfo widget = WidgetByID(widgetID);
if (widget != null && widget.label != null)
{
fontsize = widget.label.fontSize;
}
return fontsize;
}
public bool SetLocalPosition(int widgetID, float x, float y, float z)
{
WidgetInfo widget = WidgetByID(widgetID);
if (widget != null && widget.gameObject != null)
{
//LuaFramework.TransformHelper.SetLocalPosition(widget.gameObject, x, y, z);
return true;
}
return false;
}
public bool SetLocalPositionX(int widgetID, float x)
{
WidgetInfo widget = WidgetByID(widgetID);
if (widget != null && widget.gameObject != null)
{
//LuaFramework.TransformHelper.SetLocalPositionX(widget.gameObject, x);
return true;
}
return false;
}
lua代码:
每个页面对象上都挂载了一个LuaGameObjectHelper.cs对象,用于记录ID、路径、对象和实现方法。如下:
使用工具可以自动生成lua页面脚本和lua控制页面的脚本以及ID映射脚本:
生成脚本如下: