unity调用外部的fish.lua文件
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;
public class HotFixScripts : MonoBehaviour
{
private LuaEnv luaEnv;
void Start () {
luaEnv=new LuaEnv();
luaEnv.AddLoader(MyLoadder);
luaEnv.DoString("require'fish'");
}
void Update () {
}
private byte[] MyLoadder(ref string Filepath)
{
string absPath = @"F:\MyWork\Project\XluaProjects\PlayerGamePackage\" + Filepath+".lua.txt";
return System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(absPath));
}
void OnDisable()
{
luaEnv.DoString("require'fishDispose'");
}
void OnDestroy()
{
luaEnv.Dispose();
}
}
fish.lua 修改Unity内的Treasour.cs内的CreatePrize方法
--1.1
local UnityEngine=CS.UnityEngine
xlua.hotfix(CS.Treasour,'CreatePrize',function(self)
for i=0,4,1 do
local go=UnityEngine.GameObject.Instantiate(self.gold, self.transform.position + UnityEngine.Vector3(-10+ i * 30, 0, 0), self.transform.rotation);
go.transform.SetParent(go.transform,self.cavas)
local go1=UnityEngine.GameObject.Instantiate(self.diamands, self.transform.position + UnityEngine.Vector3(0, 30, 0)+UnityEngine.Vector3(-10+ i * 40, 0, 0), self.transform.rotation);
go1.transform.SetParent(go1.transform,self.cavas)
end
end)
fishDispose.lua 释放Xlua
xlua.hotfix(CS.Treasour,'CreatePrize',nil)
被修改的Treasour.cs(类要添加[HotFix],修改的方法要添加 [LuaCallCSharp])
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XLua;
/// <summary>
/// 宝藏
/// </summary>
[Hotfix]
public class Treasour : MonoBehaviour
{
private Button but;
private Image img;
public GameObject gold;
public GameObject diamands;
public GameObject cdView;
public Transform cavas;
private bool isDrease;
private void Awake()
{
but = GetComponent<Button>();
but.onClick.AddListener(OpenTreasour);
img = GetComponent<Image>();
}
void OpenTreasour()
{
if (img.color.a != 1)
{
return;
}
cdView.SetActive(true);
Gun.Instance.GoldChange(Random.Range(100, 200));
Gun.Instance.DiamandsChange(Random.Range(10, 50));
CreatePrize();
isDrease = true;
}
[LuaCallCSharp]
private void CreatePrize()
{
for (int i = 0; i < 5; i++)
{
GameObject go = Instantiate(gold, transform.position + new Vector3(-10f + i * 30, 0, 0), transform.rotation);
go.transform.SetParent(cavas);
GameObject go1 = Instantiate(diamands, transform.position + new Vector3(0, 30, 0) + new Vector3(-10f + i * 30, 0, 0), transform.rotation);
go1.transform.SetParent(cavas);
}
}
void Start()
{
}
void Update()
{
if (isDrease)
{
img.color -= new Color(0, 0, 0, Time.deltaTime * 10);
if (img.color.a <= 0.2)
{
img.color = new Color(img.color.r, img.color.g, img.color.b, 0);
isDrease = false;
}
}
else
{
img.color += new Color(0, 0, 0, Time.deltaTime * 0.01f);
if (img.color.a >= 0.9)
{
img.color = new Color(img.color.r, img.color.g, img.color.b, 1);
cdView.SetActive(false);
}
}
}
}