UnityExplorer/src/Runtime/UnityCrashPrevention.cs

47 lines
1.8 KiB
C#
Raw Normal View History

2022-04-12 00:27:20 +10:00
using System;
using System.Collections.Generic;
using System.Linq;
2022-04-12 00:27:20 +10:00
using System.Reflection;
using UnityEngine;
namespace UnityExplorer.Runtime
{
internal static class UnityCrashPrevention
{
static readonly HarmonyLib.Harmony harmony = new($"{ExplorerCore.GUID}.crashprevention");
2022-04-12 00:27:20 +10:00
internal static void Init()
2022-04-12 00:27:20 +10:00
{
TryPatch<Canvas>("get_renderingDisplaySize", nameof(Canvas_renderingDisplaySize_Prefix));
IEnumerable<MethodBase> patched = harmony.GetPatchedMethods();
if (patched.Any())
ExplorerCore.Log(
$"Initialized UnityCrashPrevention for: {string.Join(", ", patched.Select(it => $"{it.DeclaringType.Name}.{it.Name}").ToArray())}");
}
internal static void TryPatch<T>(string orig, string prefix, Type[] argTypes = null)
{
try
{
2022-04-12 00:27:20 +10:00
harmony.Patch(
HarmonyLib.AccessTools.Method(typeof(T), orig, argTypes),
2022-04-12 00:27:20 +10:00
new HarmonyLib.HarmonyMethod(HarmonyLib.AccessTools.Method(typeof(UnityCrashPrevention), prefix)));
}
catch //(Exception ex)
{
2022-04-12 00:27:20 +10:00
//ExplorerCore.Log($"Exception patching {typeof(T).Name}.{orig}: {ex}");
}
}
// In Unity 2020 they introduced "Canvas.renderingDisplaySize".
// If you try to get the value on a Canvas which has a renderMode value of WorldSpace and no worldCamera set,
2022-02-24 19:26:01 +11:00
// the game will Crash (I think from Unity trying to read from null ptr).
2022-04-12 00:27:20 +10:00
internal static void Canvas_renderingDisplaySize_Prefix(Canvas __instance)
{
if (__instance.renderMode == RenderMode.WorldSpace && !__instance.worldCamera)
2022-04-12 00:27:20 +10:00
throw new InvalidOperationException("Canvas is set to RenderMode.WorldSpace but not worldCamera is set.");
}
}
}