Files
BoneSync/BoneSync/Patching/UnityEventPatching.cs

89 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BoneSync.Data;
using HarmonyLib;
using StressLevelZero.Interaction;
using UnityEngine;
using UnityEngine.Events;
namespace BoneSync.Patching
{
public class UnityEventPatch<T>
{
private static Dictionary<int, UnityEventPatch<T>> patches = new Dictionary<int, UnityEventPatch<T>>();
private T arg;
private UnityEvent unityEvent;
private Func<T, bool> handler;
//private UnityAction listener;
//private float lastInvokeTime = 0f;
//private float invokeCooldown = 0.05f;
private UnityEventPatch(T arg, UnityEvent unityEvent, Func<T, bool> handler)
{
this.arg = arg;
this.unityEvent = unityEvent;
this.handler = handler;
//listener = (UnityAction)Listener;
}
public bool TryInvoke()
{
bool allowInvokeResult = handler(arg);
SyncLogger.Debug("TryInvoke " + allowInvokeResult);
return allowInvokeResult;
}
private void PatchUnityEvent()
{
if (unityEvent == null) return;
patches[unityEvent.GetHashCode()] = this;
//unityEvent.AddListener(listener);
}
private void UnpatchUnityEvent()
{
if (unityEvent == null) return;
patches.Remove(unityEvent.GetHashCode());
}
public static UnityEventPatch<T> Patch(T arg, UnityEvent unityEvent, Func<T, bool> handler)
{
if (patches.TryGetValue(unityEvent.GetHashCode(), out UnityEventPatch<T> oldPatch))
{
oldPatch.UnpatchUnityEvent();
}
UnityEventPatch<T> patch = new UnityEventPatch<T>(arg, unityEvent, handler);
patch.PatchUnityEvent();
return patch;
}
public static UnityEventPatch<T> TryGetPatch(UnityEvent unityEvent)
{
if (!patches.ContainsKey(unityEvent.GetHashCode())) return null;
return patches[unityEvent.GetHashCode()];
}
}
/*[HarmonyPatch(typeof(UnityEvent))]
internal class UnityEventPatches
{
[HarmonyPatch(nameof(UnityEvent.Invoke)), HarmonyPrefix]
private static bool InvokePrefix(UnityEvent __instance)
{
if (CallPatchedMethods.allowPatchedMethodCall) return true;
UnityEventPatch<ButtonToggle> patch = UnityEventPatch<ButtonToggle>.TryGetPatch(__instance);
if (patch != null)
{
return patch.TryInvoke();
}
return true;
}
}*/
}