Cache pokemon in PokemonParty so they're not garbage collected.

This commit is contained in:
Deukhoofd 2020-08-25 17:56:57 +02:00
parent b1f134c2a1
commit 2ded1d3ceb
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
1 changed files with 15 additions and 3 deletions

View File

@ -8,6 +8,7 @@ namespace PkmnLibSharp.Battling
{
public class PokemonParty : PointerWrapper, IEnumerable<Pokemon>
{
private Pokemon?[]? _cache;
private ReadOnlyNativePtrArray<Pokemon>? _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<Pokemon?> GetEnumerator()
@ -90,6 +101,7 @@ namespace PkmnLibSharp.Battling
{
pokemon?.MarkAsDeleted();
}
_cache = null;
}