https://metaplay.io logo
Best pattern to inform PlayerModel in serialized s...
# questions-and-feedback
d
I would like to call an event on the ClientListener from a subclass serialized within a PlayerModel, e.g (with dumb names, sorry in advance): - I have a method that handles adding Coins (AddCoins) in a PlayerCoinsModel - Within the OnPackBoughtAction, I call player.PlayerCurrenciesModel.AddCoins(X) - I want AddCoins() to call player.ClientListener.OnCoinsAdd(amount) so that I don't have to add it manually alongside each player.PlayerCurrenciesModel.AddCoins calls. Thus, I need my subclasses to "know" their parent PlayerModel. What would be the best pattern within Metaplay constraints to that?
j
Heya! I think there's 3 main approaches: 1. Add a
IPlayerModelClientListener
member to your
PlayerCurrenciesModel
. Then in
IMetaplayLifecycleDelegate.OnSessionStartedAsync
, also set the instance to the sub model. e.g.
Copy code
cs
async Task IMetaplayLifecycleDelegate.OnSessionStartedAsync()
{
    // Hook up to updates in PlayerModel.
    MetaplayClient.PlayerModel.PlayerCurrenciesModel.ClientListener = this;
    MetaplayClient.PlayerModel.ClientListener = this;
    ...
}
2. Pass
PlayerModel
to the subclass in `OnDeserialized`:
Copy code
cs
[MetaOnDeserialized]
public void OnDeserialized()
{
  // Note you have to pass PlayerModel and it can't be ClientListener as it is not yet set in the deserialization callbacks
  PlayerCurrenciesModel.PlayerModel = this;
}
3. Add a helper
PlayerModel.AddCoins()
that can then modify the
PlayerCurrenciesModel
, and invoke the listener. Let me know if you'd like further info on any of the proposed solutions. As a side note, we're not super happy with the way client listeners (partially due to this and other issues) work, but unfortunately changing it is fairly low on the priority list. :/