Do you need to make a copy of token data before sending along with an event?

I just fixed a bug in my game. I found that the token data that sends along with an event is not right. I have to make a copy of it before sending to fix this bug. I assume it's because the data has been changed instantly after the sending event codes. However the sending event has not happened yet. When Bolt was trying to send the event, the new data are sent.

Example codes:
Class DataClassA: IProtocolToken, ICloneable {
    int a;
    public object Clone()
    {
        return (DataClassA)MemberwiseClone();
    }
}

void SendEventFunction_BuggedVersionj(){
    var dataToSend = new DataClassA(){ a = 1};
    var evnt = EventA.Create();
    evnt.tokenData = dataToSend;
    evnt.send();
    dataToSend.a = 2; // change data in the same frame
}

void SendEventFunction_RightVersion(){
    var dataToSend = new DataClassA(){ a = 1};
    var evnt = EventA.Create();
    evnt.tokenData = dataToSend.Clone() as DataClassA;
    evnt.send();
    dataToSend.a = 2; // change data in the same frame
}

Comments

  • Hello @SPF ,

    When you pass a reference to your Token to the Event, it's just a reference, so yes, if you change it right after assigning the reference, you will be changing the same data.

    Can you describe a situation that you need to change a Token right after assigning it to an Event?
    We don't make a copy of your Token when you assign it, as you may want to reuse it in a future call.

    --
    Ramon Melo
    Photon Bolt Team
  • SPF
    SPF
    edited May 2021
    Thanks @ramonmelo , then I'll copy them. They change quite frequently in my project because my main data types are all extended from `IProtocolToken`. So it's handy to pass them as token in event.

    Example situation:
    My game is a card game, and each `CardData` is extended from `IProtocolToken`. It's quite often that a `CardData` needs to be passed as a token along with events. The instances of `CardData` are all saved in the server's data model, meaning they exist throughout the whole game. And as we know cards are buffed frequently during a game. That's why after passing them as tokens, they still can be changed quite often.