From 2ded1d3cebe7138e20194f7058395acad44f53ab Mon Sep 17 00:00:00 2001 From: Deukhoofd Date: Tue, 25 Aug 2020 17:56:57 +0200 Subject: [PATCH] Cache pokemon in PokemonParty so they're not garbage collected. --- PkmnLibSharp/Battling/PokemonParty.cs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/PkmnLibSharp/Battling/PokemonParty.cs b/PkmnLibSharp/Battling/PokemonParty.cs index 97f1352..13eb784 100644 --- a/PkmnLibSharp/Battling/PokemonParty.cs +++ b/PkmnLibSharp/Battling/PokemonParty.cs @@ -8,6 +8,7 @@ namespace PkmnLibSharp.Battling { public class PokemonParty : PointerWrapper, IEnumerable { + private Pokemon?[]? _cache; private ReadOnlyNativePtrArray? _party; internal PokemonParty(IntPtr ptr) : base(ptr){} @@ -18,10 +19,15 @@ namespace PkmnLibSharp.Battling public PokemonParty(Pokemon?[] pokemon) : base( Creaturelib.Generated.CreatureParty.ConstructFromArray(pokemon.ArrayPtr(), (ulong) pokemon.Length)) { - for (var index = 0; index < pokemon.Length; index++) - pokemon[index] = null; + _cache = pokemon; } - + + protected internal override void Initialize(IntPtr ptr) + { + base.Initialize(ptr); + _cache = Party.ToArray(); + } + public virtual Pokemon this[int i] => GetAtIndex((ulong) i); public Pokemon GetAtIndex(ulong index) @@ -34,12 +40,16 @@ namespace PkmnLibSharp.Battling public void Switch(ulong indexA, ulong indexB) { Creaturelib.Generated.CreatureParty.Switch(Ptr, indexA, indexB); + var temp = _cache![indexA]; + _cache[indexA] = _cache[indexB]; + _cache[indexB] = temp; } public Pokemon SwapInto(ulong indexA, Pokemon pokemon) { var ptr = IntPtr.Zero; Creaturelib.Generated.CreatureParty.SwapInto(ref ptr, Ptr, indexA, pokemon.Ptr).Assert(); + _cache![indexA] = pokemon; if (TryResolvePointer(ptr, out Pokemon? newPokemon)) return newPokemon!; return Constructor.Active.ConstructPokemon(ptr)!; @@ -66,6 +76,7 @@ namespace PkmnLibSharp.Battling public void PackParty() { Creaturelib.Generated.CreatureParty.PackParty(Ptr); + _cache = Party.ToArray(); } public IEnumerator GetEnumerator() @@ -90,6 +101,7 @@ namespace PkmnLibSharp.Battling { pokemon?.MarkAsDeleted(); } + _cache = null; }