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

xiaoxiao2021-02-27  162

用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"));       }  

转载请注明原文地址: https://www.6miu.com/read-16522.html

最新回复(0)