From 229a1a6509b8b418ae71f680076f68883ded37ca Mon Sep 17 00:00:00 2001 From: MrGadget <9826063+MrGadget1024@users.noreply.github.com> Date: Tue, 7 Feb 2023 23:02:55 -0500 Subject: [PATCH] perf: Distance Interest Management caches custom ranges to avoid runtime TryGetComponent overhead (#3372) * fix: Distance Interest Mgmt static dictionary * Clear on Reset * Allow for changing range at runtime * Use OnSpawned / OnDestroyed * reverted default visRange * Update DistanceInterestManagement.cs * Update DistanceInterestManagement.cs --------- Co-authored-by: mischa <16416509+vis2k@users.noreply.github.com> --- .../Distance/DistanceInterestManagement.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs index add6f4203..044155877 100644 --- a/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs +++ b/Assets/Mirror/Components/InterestManagement/Distance/DistanceInterestManagement.cs @@ -14,16 +14,32 @@ public class DistanceInterestManagement : InterestManagement public float rebuildInterval = 1; double lastRebuildTime; + // cache custom ranges to avoid runtime TryGetComponent lookups + readonly Dictionary CustomRanges = new Dictionary(); + // helper function to get vis range for a given object, or default. + [ServerCallback] int GetVisRange(NetworkIdentity identity) { - return identity.TryGetComponent(out DistanceInterestManagementCustomRange custom) ? custom.visRange : visRange; + return CustomRanges.TryGetValue(identity, out DistanceInterestManagementCustomRange custom) ? custom.visRange : visRange; } [ServerCallback] public override void Reset() { lastRebuildTime = 0D; + CustomRanges.Clear(); + } + + public override void OnSpawned(NetworkIdentity identity) + { + if (identity.TryGetComponent(out DistanceInterestManagementCustomRange custom)) + CustomRanges[identity] = custom; + } + + public override void OnDestroyed(NetworkIdentity identity) + { + CustomRanges.Remove(identity); } public override bool OnCheckObserver(NetworkIdentity identity, NetworkConnectionToClient newObserver)