0

So I have some weird error that I cant get manage to resolve:

I am making a type of racing game, there is a class RaceManager that contains all unique Checkpoints and a class RaceAgent which is on a car and also contains the checkpoints of the RaceManager, called unpassedCPs. Each time the car passes on its targetCheckpoint, it will remove it from unpassedCPs.

However if I want to add the first checkpoint to unpassedCPs, so that the cars have to return to the start/finish to complete a round, each car will also add it to the RaceManager's checkpoints.

RaceAgent.cs:

void Setup(){ //gets called at beginning and on new round; not when finished
    unpassedCPs = RaceManager.rm.checkpoints; //copy all cps
    if(laps > 0){ //true when roundcourse, else it will finish at last checkpoint
    //if i comment out next line, RaceManager will not add its first checkpoint, but here we are adding to RaceAgents' unpassedCPs
        unpassedCPs.Add(RaceManager.rm.checkpoints[0]); //for returning back to start/finish

    }

    SetTargetCP(RaceManager.rm.checkpoints[0]);
}
Mc Midas
  • 189
  • 1
  • 5
  • 17
  • Can you provide more details and full code utilized, and the error that you are facing. – Riaz Raza Jan 20 '18 at 14:13
  • Duplicate of [Changes made on "copy" list are reflecting original list - c#](https://stackoverflow.com/questions/39633104/changes-made-on-copy-list-are-reflecting-original-list-c-sharp) – Cee McSharpface Jan 20 '18 at 14:17
  • 1
    If `RaceManager.rm.checkpoints` is a reference-type structure (like a list), the line `unpassedCPs = RaceManager.rm.checkpoints` will not copy values but will copy references to `checkpoints`. Any change to `unpassedCPs` will also change `RaceManager.rm.checkpoints`. – ethane Jan 20 '18 at 14:17
  • The code you have posted does not help to show the issue you are having. – CodingYoshi Jan 20 '18 at 14:17

1 Answers1

2
unpassedCPs = RaceManager.rm.checkpoints; //copy all cps

Unless the checkpoints is a property and contains codes in its get to create a copy of the checkpoints, this line does not copy all cps. Instead after the statement unpassedCPs refer to the same collection as RaceManager.rm.checkpoints, so when you run

unpassedCPs.Add(RaceManager.rm.checkpoints[0])

is similar as running RaceManager.rm.checkpoints.Add(RaceManager.rm.checkpoints[0])

To solve your issue, you need to create a new List base on the checkpints, e.g.:

unpassedCPs = new List<Checkpoint>(RaceManager.rm.checkpoints);
Evan Huang
  • 1,245
  • 9
  • 16