Skip to content

Commit

Permalink
Added BepInEx.CatchUnityEventExceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
ManlyMarco committed May 24, 2021
1 parent 8647dbc commit f1a40ff
Show file tree
Hide file tree
Showing 5 changed files with 204 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{29D4BA63-9886-4C1A-9AAA-D9EBAF1AC9BA}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BepInEx</RootNamespace>
<AssemblyName>BepInEx.CatchUnityEventExceptions</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>embedded</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\bin\BepInEx\plugins\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>embedded</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\bin\BepInEx\plugins\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<Reference Include="0Harmony">
<HintPath>..\lib\0Harmony.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="BepInEx">
<HintPath>..\lib\BepInEx.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System.Core" />
<Reference Include="UnityEngine, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\UnityEngine.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="CatchUnityEventExceptionsPlugin.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>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}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\IllusionLibs.BepInEx.Harmony.2.3.2\build\IllusionLibs.BepInEx.Harmony.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\IllusionLibs.BepInEx.Harmony.2.3.2\build\IllusionLibs.BepInEx.Harmony.targets'))" />
</Target>
</Project>
Original file line number Diff line number Diff line change
@@ -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<SceneManager, UnityAction<Scene, Scene>>("activeSceneChanged", action => action.Invoke(previousActiveScene, newActiveScene));
}

[HarmonyPrefix]
[HarmonyPatch(typeof(SceneManager), "Internal_SceneLoaded")]
private static bool Internal_SceneLoadedHook(Scene scene, LoadSceneMode mode)
{
return !SafeInvokeEvent<SceneManager, UnityAction<Scene, LoadSceneMode>>("sceneLoaded", action => action.Invoke(scene, mode));
}

[HarmonyPrefix]
[HarmonyPatch(typeof(SceneManager), "Internal_SceneUnloaded")]
private static bool Internal_SceneUnloadedHook(Scene scene)
{
return !SafeInvokeEvent<SceneManager, UnityAction<Scene>>("sceneUnloaded", action => action.Invoke(scene));
}

private static bool SafeInvokeEvent<T, T2>(string eventFieldName, Action<T2> 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;
}
}
}
}
36 changes: 36 additions & 0 deletions BepInEx.CatchUnityEventExceptions/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -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)]
6 changes: 6 additions & 0 deletions BepInEx.Utility.sln
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.

0 comments on commit f1a40ff

Please sign in to comment.