打补丁
接着打开Cube脚本,修改如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;
[Hotfix]
public class Cube : MonoBehaviour
{
private Rigidbody rigidbody;
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody>();
}
[LuaCallCSharp]
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
rigidbody.AddForce(Vector3.up*200);
}
}
}
我们先引入XLua命名空间,然后再要热更的代码上打[Hotfix]标签,在热更的代码上打,[LuaCallCSharp]标签。保存代码退出。
此时C#代码修改,所以需要运行那两步,重新编译。之后在打开Test.lua.txt文件输入一下内容,讲原来的W键修改为S键。
local UnityEngine=CS.UnityEngine
xlua.hotfix(CS.Cube,'Update',function(self)--热更的脚本名称,需要热更的方法,热更的内容
--热乎代码块
if(UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.S)) then
self.rigidbody:AddForce(UnityEngine.Vector3.up*200);
end
end)
之后保存代码文件。返回代unity中然后运行,此时发现按住W键不管用,按S键cube跳起来了。
创建更新资源,AB包
我们在场景中新建一个Sphere游戏物体,然后给物体上添加Rigidbody组件,然后给这个物体添加上Cube脚本。
然后讲Sphere游戏物体设置成预制体,然后点击Sphere预制体,在Inspector面板最下面看到
将这里修改成
然后新建文件夹Editor,在里面新建脚本CreatAssetBundles,在里面输入代码来打包我们的AB包。
using UnityEditor;
using System.IO;
public class CreatAssetBundles
{
[MenuItem("Assets/Build AssetBundles")]
static void BuildAssetBundles()
{
string dir = "AssetBundles";
if(!Directory.Exists(dir))//如果该文件夹不存在
{
Directory.CreateDirectory(dir);
}
BuildPipeline.BuildAssetBundles(dir,BuildAssetBundleOptions.None,BuildTarget.StandaloneWindows64);//填写对应的平台
}
}
我们就可以在Assets菜单下找到我们新建的选项,点击Build AssetBundles,会发现控制台报错Error building Player because scripts had compiler errors,这是因为在XLua文件下的Examples文件有冲突所导致,现在我们将该文件夹删除。
然后选择 Clear Generated Code
然后再重新生成注入,点击Generate Code 点击Hotfix Inject In Editor。
在Assets菜单下找到我们新建的选项,点击Build AssetBundles。发现并没有报错!
我们打开项目文件的根目录,发现里面已经生成好了sphere.unity3d的ab文件。