1.介绍
热重载是在 Editor 打开的状态下创建或编辑脚本并立即应用脚本行为的过程。无需重新启动应用程序和 Editor 即可使更改生效。更改并保存脚本时,Unity 会热重载所有当前加载的脚本数据。
2.实现原理
1.OperaComponentUpdateSystem.cs
点击R重新装载Logic_.dl,Logic_pdb
if (Input.GetKeyDown(KeyCode.R))
{
//重新读取"Codes/Hotfix/","Codes/HotfixView/"目录打出来的dll,pdb
CodeLoader.Instance.LoadHotfix();
//将重新读取的反射类型添加到EventSystem
Game.EventSystem.Add(CodeLoader.Instance.GetTypes());
//重新装载反射
Game.EventSystem.Load();
Log.Debug("hot reload success!");
}
2.BuildAssemblieEditor.cs
编译dll
[MenuItem("Tools/BuildData _F7")]
public static void BuildData()
{
//编译Model/ModelView下的cs为data.dll/pdb
BuildAssemblieEditor.BuildMuteAssembly("Data", new []
{
"Codes/Model/",
"Codes/ModelView/",
}, Array.Empty<string>(), CodeOptimization.Debug);
}
[MenuItem("Tools/BuildLogic _F8")]
public static void BuildLogic()
{
string[] logicFiles = Directory.GetFiles(Define.BuildOutputDir, "Logic_*");
foreach (string file in logicFiles)
{
File.Delete(file);
}
int random = RandomHelper.RandomNumber(100000000, 999999999);
string logicFile = $"Logic_{random}";
//编译Hotfix/HotfixView下的cs为Logic_.dll/pdb
BuildAssemblieEditor.BuildMuteAssembly(logicFile, new []
{
"Codes/Hotfix/",
"Codes/HotfixView/",
}, new[]{Path.Combine(Define.BuildOutputDir, "Data.dll")}, CodeOptimization.Debug);
}
3.?CodeLoader.cs
?重新读取"Codes/Hotfix/","Codes/HotfixView/"目录打出来的dll,pdb
public void LoadHotfix()
{
// Unity在这里搞了个优化,认为同一个路径的dll,返回的程序集就一样。所以这里每次编译都要随机名字
string[] logicFiles = Directory.GetFiles(Define.BuildOutputDir, "Logic_*.dll");
if (logicFiles.Length != 1)
{
throw new Exception("Logic dll count != 1");
}
//读取logic_.dll/pdb
string logicName = Path.GetFileNameWithoutExtension(logicFiles[0]);
byte[] assBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, $"{logicName}.dll"));
byte[] pdbBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, $"{logicName}.pdb"));
Assembly hotfixAssembly = Assembly.Load(assBytes, pdbBytes);
//将data.dll和logic_.dll的反射类型保存给allTypes变量
List<Type> listType = new List<Type>();
listType.AddRange(this.assembly.GetTypes());
listType.AddRange(hotfixAssembly.GetTypes());
this.allTypes = listType.ToArray();
}
4.EventSystem.cs
重新加载dll的反射类型,并重新调用所有loaders队列中的实体的loadsystem类的run方法
public void Add(Type[] addTypes)
{
this.allTypes.Clear();
foreach (Type addType in addTypes)
{
this.allTypes[addType.FullName] = addType;
}
this.types.Clear();
//获取所有继承BaseAttribute的类型
List<Type> baseAttributeTypes = GetBaseAttributes(addTypes);
foreach (Type baseAttributeType in baseAttributeTypes)
{
foreach (Type type in addTypes)
{
if (type.IsAbstract)
{
continue;
}
object[] objects = type.GetCustomAttributes(baseAttributeType, true);
if (objects.Length == 0)
{
continue;
}
//将同类型的特性存在一个字典
this.types.Add(baseAttributeType, type);
}
}
this.typeSystems = new TypeSystems();
//遍历所有ObjectSystemAttribute
foreach (Type type in this.GetTypes(typeof (ObjectSystemAttribute)))
{
object obj = Activator.CreateInstance(type);
if (obj is ISystemType iSystemType)
{
//将每个类打上ObjectSystem标签的类存字典
OneTypeSystems oneTypeSystems = this.typeSystems.GetOrCreateOneTypeSystems(iSystemType.Type());
oneTypeSystems.Add(iSystemType.SystemType(), obj);
}
}
this.allEvents.Clear();
//遍历所有EventAttribute
foreach (Type type in types[typeof (EventAttribute)])
{
IEvent obj = Activator.CreateInstance(type) as IEvent;
if (obj == null)
{
throw new Exception($"type not is AEvent: {obj.GetType().Name}");
}
Type eventType = obj.GetEventType();
if (!this.allEvents.ContainsKey(eventType))
{
this.allEvents.Add(eventType, new List<object>());
}
//将同一个eventType的类存入allEvents字典
this.allEvents[eventType].Add(obj);
}
}
public void Load()
{
while (this.loaders.Count > 0)
{
//取到loaders队列的entity
long instanceId = this.loaders.Dequeue();
Entity component;
if (!this.allEntities.TryGetValue(instanceId, out component))
{
continue;
}
if (component.IsDisposed)
{
continue;
}
//获得entity继承ILoadSystem的类
List<object> iLoadSystems = this.typeSystems.GetSystems(component.GetType(), typeof (ILoadSystem));
if (iLoadSystems == null)
{
continue;
}
//loaders取出的instanceId压入loaders2
this.loaders2.Enqueue(instanceId);
foreach (ILoadSystem iLoadSystem in iLoadSystems)
{
try
{
//运行load方法
iLoadSystem.Run(component);
}
catch (Exception e)
{
Log.Error(e);
}
}
}
//将loaders和loaders2交换,方便下次使用
ObjectHelper.Swap(ref this.loaders, ref this.loaders2);
}
3.热重载的使用
1.运行前按F7,F8编译data.dll和logic_.dll
2.运行中修改"Codes/Hotfix/","Codes/HotfixView/"目录下的代码时按F8然后R就能实现热重载
3.建议实体的初始化方法封装一个函数,在AwakeSystem调用的,然后也要写个LoadSystem调用该初始化方法,才可以实现实体的初始化刷新热重载
|