37 lines
1.4 KiB
Markdown
37 lines
1.4 KiB
Markdown
|
|
这节课在点击回合转换按钮,清空卡牌的时候出现的错误,当时的代码是
|
||
|
|
```
|
||
|
|
public void OnPlayerTurnEnd()
|
||
|
|
{
|
||
|
|
for (int i = 0; i < handCardObjectList.Count; i++)
|
||
|
|
{
|
||
|
|
DiscardDeck(handCardObjectList[i]);
|
||
|
|
}
|
||
|
|
handCardObjectList.Clear();
|
||
|
|
|
||
|
|
}
|
||
|
|
```
|
||
|
|
由于我们使用DiscardDeck函数,每次都会将手牌列表(handCardObjectList)的第一位移除,这样会导致我们的部分卡牌不能正确的被移除.
|
||
|
|
以下是Deepseek的解释.
|
||
|
|
在`OnPlayerTurnEnd`方法中,当遍历手牌列表并调用`DiscardDeck`时,正向循环会导致部分卡牌未被处理。每次移除元素后,列表的索引和长度发生变化,导致后续元素被跳过。以下是解决方案:
|
||
|
|
|
||
|
|
**步骤解释:**
|
||
|
|
|
||
|
|
1. **问题分析:** 正向遍历列表时,移除元素会导致后续索引错位,部分卡牌未被处理。
|
||
|
|
|
||
|
|
2. **解决方案:** 改为从后向前遍历列表,这样移除元素不会影响未处理的索引。
|
||
|
|
|
||
|
|
3. **代码调整:** 修改循环结构,确保所有卡牌都被正确弃用。
|
||
|
|
|
||
|
|
修改后的代码为:
|
||
|
|
```
|
||
|
|
public void OnPlayerTurnEnd()
|
||
|
|
{
|
||
|
|
// 从后向前遍历,避免索引错位
|
||
|
|
for (int i = handCardObjectList.Count - 1; i >= 0; i--)
|
||
|
|
{
|
||
|
|
DiscardDeck(handCardObjectList[i]);
|
||
|
|
}
|
||
|
|
// 清空列表(此时应已为空,但确保万无一失)
|
||
|
|
handCardObjectList.Clear();
|
||
|
|
}
|
||
|
|
```
|