diff --git a/BepInEx.CatchUnityEventExceptions/BepInEx.CatchUnityEventExceptions.csproj b/BepInEx.CatchUnityEventExceptions/BepInEx.CatchUnityEventExceptions.csproj new file mode 100644 index 0000000..6bda9de --- /dev/null +++ b/BepInEx.CatchUnityEventExceptions/BepInEx.CatchUnityEventExceptions.csproj @@ -0,0 +1,65 @@ + + + + + Debug + AnyCPU + {29D4BA63-9886-4C1A-9AAA-D9EBAF1AC9BA} + Library + Properties + BepInEx + BepInEx.CatchUnityEventExceptions + v3.5 + 512 + true + + + + + true + embedded + false + ..\bin\BepInEx\plugins\ + DEBUG;TRACE + prompt + 4 + true + + + embedded + true + ..\bin\BepInEx\plugins\ + TRACE + prompt + 4 + true + true + + + + ..\lib\0Harmony.dll + False + + + ..\lib\BepInEx.dll + False + + + + False + ..\lib\UnityEngine.dll + False + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + \ No newline at end of file diff --git a/BepInEx.CatchUnityEventExceptions/CatchUnityEventExceptionsPlugin.cs b/BepInEx.CatchUnityEventExceptions/CatchUnityEventExceptionsPlugin.cs new file mode 100644 index 0000000..9fc8142 --- /dev/null +++ b/BepInEx.CatchUnityEventExceptions/CatchUnityEventExceptionsPlugin.cs @@ -0,0 +1,91 @@ +using System; +using BepInEx.Logging; +using HarmonyLib; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.SceneManagement; + +namespace BepInEx +{ + [BepInPlugin(GUID, PluginName, Version)] + public class CatchUnityEventExceptionsPlugin : BaseUnityPlugin + { + public const string GUID = "CatchUnityEventExceptions"; + public const string PluginName = "Catch Unity Event Exceptions"; + public const string Version = "1.0"; + + private static new ManualLogSource Logger; + + private void Awake() + { + Logger = base.Logger; + + try + { + HarmonyLib.Harmony.CreateAndPatchAll(typeof(Hooks), GUID); + } + catch (Exception e) + { + Logger.LogMessage(GUID + " is not compatible with version of Unity that this game is using!"); + Debug.LogException(e); + enabled = false; + } + } + + private static class Hooks + { + [HarmonyPrefix] + [HarmonyPatch(typeof(SceneManager), "Internal_ActiveSceneChanged")] + private static bool Internal_ActiveSceneChangedHook(Scene previousActiveScene, Scene newActiveScene) + { + return !SafeInvokeEvent>("activeSceneChanged", action => action.Invoke(previousActiveScene, newActiveScene)); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SceneManager), "Internal_SceneLoaded")] + private static bool Internal_SceneLoadedHook(Scene scene, LoadSceneMode mode) + { + return !SafeInvokeEvent>("sceneLoaded", action => action.Invoke(scene, mode)); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SceneManager), "Internal_SceneUnloaded")] + private static bool Internal_SceneUnloadedHook(Scene scene) + { + return !SafeInvokeEvent>("sceneUnloaded", action => action.Invoke(scene)); + } + + private static bool SafeInvokeEvent(string eventFieldName, Action callHandler) where T2 : Delegate + { + try + { + var action = (T2)typeof(T).GetField(eventFieldName, AccessTools.all).GetValue(null); + if (action != null) + { + foreach (T2 handler in action.GetInvocationList()) + { + try + { + callHandler(handler); + } + catch (Exception e) + { + var eventName = typeof(T).Name + "." + eventFieldName; + Logger.LogWarning( + "Caught an exception when invoking the " + eventName + " event. PLEASE FIX THE CODE THAT CAUSED THE EXCEPTION BELOW! Without this plugin, this exception WILL cause event handlers of random plugins to randomly not be run, and it WILL create a ton of unnecessary headache for plugin authors."); + Debug.LogException(e); + } + } + } + } + catch (Exception e) + { + Logger.LogWarning("Failed to safely run events, falling back to original game code. Reason: " + e.Message); + return false; + } + + return true; + } + } + } +} \ No newline at end of file diff --git a/BepInEx.CatchUnityEventExceptions/Properties/AssemblyInfo.cs b/BepInEx.CatchUnityEventExceptions/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2379efc --- /dev/null +++ b/BepInEx.CatchUnityEventExceptions/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.InteropServices; +using static BepInEx.CatchUnityEventExceptionsPlugin; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("BepInEx.CatchUnityEventExceptions")] +[assembly: AssemblyDescription(PluginName)] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("https://github.com/BepInEx/BepInEx.Utility")] +[assembly: AssemblyProduct("BepInEx.CatchUnityEventExceptions")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("d7b4a73a-1c1a-4c52-8fa6-3b52c2240c29")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion(Version)] +[assembly: AssemblyFileVersion(Version)] \ No newline at end of file diff --git a/BepInEx.Utility.sln b/BepInEx.Utility.sln index 23755f9..e0845af 100644 --- a/BepInEx.Utility.sln +++ b/BepInEx.Utility.sln @@ -17,6 +17,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BepInEx.OptimizeIMGUI", "Be EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BepInEx.SuppressGetTypesErrorsPatcher", "BepInEx.SuppressGetTypesErrors\BepInEx.SuppressGetTypesErrorsPatcher.csproj", "{F2A30C40-4073-45AC-8325-E255BD2B011D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BepInEx.CatchUnityEventExceptions", "BepInEx.CatchUnityEventExceptions\BepInEx.CatchUnityEventExceptions.csproj", "{29D4BA63-9886-4C1A-9AAA-D9EBAF1AC9BA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -51,6 +53,10 @@ Global {F2A30C40-4073-45AC-8325-E255BD2B011D}.Debug|Any CPU.Build.0 = Debug|Any CPU {F2A30C40-4073-45AC-8325-E255BD2B011D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F2A30C40-4073-45AC-8325-E255BD2B011D}.Release|Any CPU.Build.0 = Release|Any CPU + {29D4BA63-9886-4C1A-9AAA-D9EBAF1AC9BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {29D4BA63-9886-4C1A-9AAA-D9EBAF1AC9BA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {29D4BA63-9886-4C1A-9AAA-D9EBAF1AC9BA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {29D4BA63-9886-4C1A-9AAA-D9EBAF1AC9BA}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/README.md b/README.md index dd2dc85..7a1ddef 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,6 @@ Prevents plugin hotkeys from triggering while typing in an input field. ## MessageCenter A simple plugin that shows any log entries marked as "Message" on screen. Plugins generally use the "Message" log level for things that they want the user to read. - #### How to make my mod compatible? Use the `Logger` of your plugin and call its `LogMessage` method or `Log` method and pass in `LogLevel.Message` as a parameter. You don't have to reference this plugin, and everything will work fine if this plugin doesn't exist. @@ -28,8 +27,13 @@ Please avoid abusing the messages! Only show short and clear messages that the u ## MuteInBackground Adds an option to mute a game when it loses focus, i.e. when alt-tabbed. Must be enabled in the plugin config either by editing the plugin's .cfg file or by using [ConfigurationManager](https://github.com/BepInEx/BepInEx.ConfigurationManager) +## CatchUnityEventExceptions +Makes sure all event handlers subscribed to commonly used UnityEngine events are executed, even if some of them crash. +#### Explanation +If any event handler that has been subscribed to UnityEngine events like "SceneManager.sceneLoaded" crashes, no other event handlers will be executed after this one. This can cause very hard to debug bugs, for example: Plugin A's handler crashes, which causes Plugin B's handler to not run. B's handler was supposed to initialize some fields before other code runs, but it could not do it, so now the code that expected these fields to be initialized will behave in an unexpected way. + ## SuppressGetTypesErrorsPatcher A patcher that hooks Assembly.GetTypes() and handles ReflectionTypeLoadException. Useful when game code is using Assembly.GetTypes() without handling the exception, and it crashes on plugin assemblies that have types that can't be loaded. ## OptimizeIMGUI -Reduce unnecessary GC allocations of Unity's IMGUI (OnGUI) interface system. It fixes the passive GC allocations that happen every frame caused by using any OnGUI code at all, and reduces GC allocations for OnGUI code. +Reduce unnecessary GC allocations of Unity's IMGUI (OnGUI) interface system. It fixes the passive GC allocations that happen every frame caused by using any OnGUI code at all, and reduces GC allocations for OnGUI code. \ No newline at end of file