using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MoonSharp.Interpreter;
using System.IO;
using UnityEngine.UI;
public class LuaHelper : MonoBehaviour
{
[SerializeField]
TextAsset _commonLua;
Script script;
public RawImage img;
void Start ()
{
Setup ();
}
public void Setup ()
{
Debug.Log ("Setup");
script = new Script ();
script.Globals ["PrintLog"] = (System.Action<object>)PrintLog;
script.DoString (_commonLua.text);
// グローバル変数セットアップ
// UserInfo注入
UserData.RegisterType<UserInfo> ();
ReloadCommonData ();
script.Call (script.Globals ["DebugFunc"], "Test Execute");
StartCoroutine (Load<TextAsset> ("sub.lua", x => ApplyLua (x)));
StartCoroutine (Load<Texture2D> ("testimg", x => {
img.texture = x;
}));
}
public bool a;
void Update ()
{
if (a) {
ReloadCommonData ();
}
}
int i;
public void ReloadCommonData ()
{
UserInfo info = GetUserInfo (i++);
var infoObj = UserData.Create (info);
script.Globals.Set ("userData", infoObj);
CallLuaFunc ("DebugUserData");
}
void CallLuaFunc (string funcName)
{
script.Call (script.Globals [funcName]);
}
void ApplyLua (TextAsset t)
{
Debug.Log ("ApplyLua");
script.DoString (t.text);
}
/// <summary>
/// 以下サンプルの場合のアセットバンドルの規則
/// ObjectName : A
/// AssetBundleName :a
/// AssetName : a
/// </summary>
IEnumerator Load<T> (string name, System.Action<T> callback) where T : Object
{
string path = Application.streamingAssetsPath + "/" + name;
byte[] b = File.ReadAllBytes (path);
var req = AssetBundle.LoadFromMemoryAsync (b);
yield return req;
var ab = req.assetBundle;
var t = ab.LoadAsset<T> (name);
callback (t);
abList.Add (ab);
}
List<AssetBundle> abList = new List<AssetBundle> ();
void OnGUI ()
{
if (GUILayout.Button ("Unload")) {
if (abList.Count > 0) {
Debug.Log ("Unload Done");
// ab.Unload (true);
foreach (var ab in abList) {
ab.Unload (false);
}
foreach (var ab in abList) {
Debug.Log (ab);
}
}
}
if (GUILayout.Button ("ExecuteSub")) {
script.Call (script.Globals ["SubFunc"]);
}
}
UserInfo userInfo;
UserInfo GetUserInfo (int i)
{
if (userInfo == null) {
userInfo = new UserInfo ();
userInfo.name = "Test";
}
userInfo.id = i;
return userInfo;
}
UserPlaceInfo GetUserPlaceInfo ()
{
return new UserPlaceInfo () {
region = Region.Hiroshima
};
}
void PrintLog (object obj)
{
Debug.Log (obj);
}
}
public class UserInfo
{
public int id;
public int hp;
public string name = "foo";
public Region region;
}
public class UserPlaceInfo
{
public Region region;
}
public enum Region
{
Tokyo = 0,
Osaka,
Hiroshima,
Hokkaido,
Okinawa
}