所以我有一些奇怪的错误,我无法解决:
我正在制作一种赛车游戏,有一个类RaceManager,它包含所有独特的Checkpoints和一个RaceAgent类,它位于汽车上,还包含RaceManager的检查点,称为unpassedCPs。每次汽车通过其targetCheckpoint时,它都会将其从unpassedCPs中删除。
但是,如果我想将第一个检查点添加到unpassedCPs,以便车辆必须返回到开始/结束以完成一轮,每辆车也会将其添加到RaceManager的检查点。
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]);
}
答案 0 :(得分:2)
unpassedCPs = RaceManager.rm.checkpoints; //copy all cps
除非checkpoints
是属性并且在其get
中包含代码以创建checkpoints
的副本,否则此行不会复制所有cps。
相反,在语句unpassedCPs
引用与RaceManager.rm.checkpoints
相同的集合之后,所以当您运行
unpassedCPs.Add(RaceManager.rm.checkpoints[0])
与运行RaceManager.rm.checkpoints.Add(RaceManager.rm.checkpoints[0])
要解决您的问题,您需要在检查点上创建一个新的List
基础,例如:
unpassedCPs = new List<Checkpoint>(RaceManager.rm.checkpoints);