这次我尝试进行本地加载ab包对之前的创建正方体进行修改,使其创建球体。
首先对之前的HoFixScripts脚本修改,使其可以获取本地的ab包
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
using System.IO;
public class HoFixScripts : MonoBehaviour {
private LuaEnv luaenv;
public static Dictionary<string, GameObject> dir = new Dictionary<string, GameObject>();
// Use this for initialization
void Awake () {
luaenv = new LuaEnv();
luaenv.AddLoader(byte_text);
luaenv.DoString("require'hello'");
}
private byte [] byte_text(ref string filepath)
{
string abs = @"D:\Lua\" + filepath +".lua.txt";
return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(abs));
}
private void OnDisable()
{
luaenv.DoString("require'fish'");
}
private void OnDestroy()
{
luaenv.Dispose();
}
public static void load(string name,string file)
{
AssetBundle ab = AssetBundle.LoadFromFile(@"D:\Game\boke_lua\AB\" + file);
GameObject ob = ab.LoadAsset <GameObject>(name);
dir.Add(name, ob);
}
public static GameObject get_object(string name)
{
return dir[name];
}
}
第二步,进行简单的打包
创立一个脚本,放在Editor文件下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEditor;
public class CreateAssetBundles {
[MenuItem ("Assets/Start")]
static void create()
{
string str = "AB";
if(Directory .Exists(str)==false)
{
Directory.CreateDirectory(str);
}
BuildPipeline.BuildAssetBundles(str, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
}
}
然后创建一个球体最为打包的内容
最后对之前的lua脚本进行修改
xlua.private_accessible(CS.Creat_cube)
xlua.hotfix(CS.Creat_cube,'Start',function(self)
CS.HoFixScripts.load('Sphere','gameobject\\sphere.ab')
for i=0,2,1 do
local go=CS.UnityEngine.GameObject.Instantiate(CS.HoFixScripts.get_object('Sphere'), self.transform.position+CS.UnityEngine.Vector3(10 * i + 5, 0, 0), self.transform.rotation);
self.print_number(self,'88')
self:print_char('bb')
end
end)
最后结果
插个题外话:要注意类型转化。比如在lua做产生随机数,调用c#的方法,但c#的Range函数有int和float类型的,一般lua是使用float的,但随机产生的值会变成float的,最后float赋值int时,会默认为0.所以在lua中要将float转化为int。