简体   繁体   中英

Recording Class Var Status while changing variable value in C#

public class TurnStatus{

    public int[,] stonesStatus;
    public bool[,] isHacked;
    public bool[,] isTrapSet;

    public TurnStatus(int[,] _stonesStatus, bool[,] _isHacked, bool[,] _isTrapSet)
    {
        stonesStatus = _stonesStatus;

        isHacked = _isHacked;
        isTrapSet = _isTrapSet;
    }

}

public class TestClass : MonoBehaviour{
    public int[,] currentStoneStatus = new int[10,10];
    public bool[,] currentIsHacked = new bool[10, 10];
    public bool[,] currentIsTrapSet = new bool[10, 10];

    List<TurnStatus> TurnStatusList = new List<TurnStatus>();

    void RecordTurnStatus()
    {
        TurnStatusList.Add(new TurnStatus(currentStoneStatus, currentIsHacked, currentIsTrapSet));
    }
}

The code is as above.

After changing the values of currentStoneStatus, currentIsHacked, and currentTrapSet, the current three variables are stored and recorded in TurnStatusList as TurnStatus class variables through the RecordTurnStatus function.

The problem here, however, is that after calling the RecordTurnStatus function and recording the current state, all of the TurnStatus variables in the list are overwritten with the most recently stored ones.

For example, if you save A, B, and C in turn in the list, the contents of the list become {C, C, C}.

I kept reviewing it, but I couldn't figure out the problem. I want your help.

This is because arrays are reference types, all the objects are pointing to the same arrays in the memory.

You should copy/clone the array, for example:

stonesStatus = _stonesStatus.Clone() as int[,];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM