Skip to content
This repository has been archived by the owner on Nov 4, 2021. It is now read-only.

Commit

Permalink
Fix: Fire CharacterMoveEvent only if the character's position change …
Browse files Browse the repository at this point in the history
…+ added cache to avoid killing the GBC
  • Loading branch information
AlexMog committed Feb 20, 2021
1 parent 3b3b3c4 commit 774f14d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
4 changes: 2 additions & 2 deletions Longship/Events/CharacterMoveEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ namespace Longship.Events
public class CharacterMoveEvent : CharacterEvent
{
public Vector3 OldPos { get; }
public Vector3 NewPos { get; set; }
public Vector3 NewPos { get; }

public CharacterMoveEvent(Character character, Vector3 oldPos) : base(character)
public CharacterMoveEvent(Character character, Vector3 oldPos, Vector3 newPos) : base(character)
{
OldPos = oldPos;
}
Expand Down
21 changes: 16 additions & 5 deletions Longship/Patches/PatchListenToCharacterMovements.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
using HarmonyLib;
using Longship.Events;
using UnityEngine;

namespace Longship.Patches
{
[HarmonyPatch(typeof(Character), "UpdateMotion")]
public class PatchListenToCharacterMovements
{
static void Prefix(Character __instance, out CharacterMoveEvent __state)
// Using a position cache to avoid over-using the Garbage collector by instancing too much vectors
private static Vector3 _positionCache = new Vector3();

static void Prefix(Character __instance)
{
__state = new CharacterMoveEvent(__instance, __instance.transform.position);
var tmp = __instance.transform.position;
_positionCache.Set(tmp.x, tmp.y, tmp.z);
}

static void Postfix(Character __instance, CharacterMoveEvent __state)
static void Postfix(Character __instance)
{
__state.NewPos = __instance.transform.position;
Longship.Instance.EventManager.DispatchEvent(__state);
if (_positionCache.Equals(__instance.transform.position))
{
return;
}

// Only fire the event if the position is different
Longship.Instance.EventManager.DispatchEvent(
new CharacterMoveEvent(__instance, _positionCache, __instance.transform.position));
}
}
}

0 comments on commit 774f14d

Please sign in to comment.