Unity热更新之C#反射加载程序集

用C#反射加载程序集的方式可以动态的从assetBundle资源包或其他资源包里加载脚本到工程中,即便是原工程中不存在的脚本。

我这里就用加载本地assetBundle的方式来进行讲解了,加载网络上的与之类似。


第一步,加载assetBundle资源,assetBundle名称为Test:


//将本地文件转为字节
FileStream fs = new FileStream(Application.dataPath + "/Test", FileMode.Open, FileAccess.Read);

byte[] buffur = new byte[fs.Length];

fs.Read(buffur, 0, (int)fs.Length);

fs.Close();

第二步,加载程序集及获取指定类型


public GameObject _gameObjectRoot;
    
public TextAsset _script;
    
public GameObject _gameobject;

StartCoroutine(BeginGetAsset(buffur));

IEnumerator BeginGetAsset(byte[] bytes)
    {
        //从内存中获取资源
        AssetBundleCreateRequest acr = AssetBundle.CreateFromMemory(bytes);
        yield return acr;
        _assetBundle = acr.assetBundle;
        //加载资源中的预设
        _gameObjectRoot = (GameObject)_assetBundle.LoadAsset("GameObjectRoot.prefab");
        //将预设创建在场景内
        yield return _gameobject = Instantiate(_gameObjectRoot);
        //获取到assetBundle中的test.DLL
        _script = (TextAsset)_assetBundle.LoadAsset("test", typeof(TextAsset));
        //C#反射取出程序集
        System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(_script.bytes);
        //加载程序集中的脚本Mytest.cs
        _gameobject.AddComponent(assembly.GetType("Mytest"));
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神码编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值