Unity购车功能Bug:Car Index自动倍增且越界消失
问题根源
BuyThisCar方法中调用ChangeCar(currentMinOne)的逻辑错误:ChangeCar的参数是索引增量值,而你传入的currentMinOne = CurrentCar - 1是当前索引减1的绝对值,这会导致CurrentCar被错误累加(比如当前索引为3时,传入2,CurrentCar变为3+2=5;后续再次点击会继续累加,最终超出子物体数量范围,车辆因无对应索引而消失)。
修复方案
方案1:直接更新按钮状态(最简)
修改BuyThisCar方法,移除错误的ChangeCar调用,直接更新按钮状态:
public void BuyThisCar() { PlayerPrefs.SetInt(ownCarIndex, 1); haveCoins -= carValue; // 替换+= -carValue,写法更直观 PlayerPrefs.SetInt("totalCoins", haveCoins); // 直接更新当前车辆的按钮状态 UseButton.GetComponent<Image>().color = GreenColor; UseButton.GetComponentInChildren<Text>().text = "Select"; ClosePanel(); }
方案2:复用现有逻辑(避免重复代码)
调用ChangeCar(0),传入增量0保持当前索引不变,触发状态刷新:
public void BuyThisCar() { PlayerPrefs.SetInt(ownCarIndex, 1); haveCoins -= carValue; PlayerPrefs.SetInt("totalCoins", haveCoins); // 增量0不改变索引,仅刷新按钮状态和车辆显示 ChangeCar(0); ClosePanel(); }
方案3:重构代码(优化结构)
抽离状态更新逻辑为单独方法,使代码职责更清晰:
// 新增:单独处理按钮状态更新 private void UpdateCarButtonState() { ownCarIndex = "CarNo" + CurrentCar; Debug.Log(ownCarIndex); var hasCar = PlayerPrefs.GetInt(ownCarIndex) == 1; UseButton.GetComponent<Image>().color = hasCar ? GreenColor : RedColor; UseButton.GetComponentInChildren<Text>().text = hasCar ? "Select" : "Buy Now"; } // 修改ChangeCar,复用状态更新方法 public void ChangeCar(int _change) { CurrentCar += _change; // 新增边界检查,防止索引越界 CurrentCar = Mathf.Clamp(CurrentCar, 0, transform.childCount - 1); ChooseCar(CurrentCar); UpdateCarButtonState(); } // 修改BuyThisCar,调用单独的状态更新 public void BuyThisCar() { PlayerPrefs.SetInt(ownCarIndex, 1); haveCoins -= carValue; PlayerPrefs.SetInt("totalCoins", haveCoins); UpdateCarButtonState(); ClosePanel(); }
额外优化:添加索引边界保护
在ChangeCar中添加Mathf.Clamp,即使出现错误增量,也能保证CurrentCar在合法范围内,避免车辆消失:
CurrentCar = Mathf.Clamp(CurrentCar, 0, transform.childCount - 1);
内容的提问来源于stack exchange,提问作者Ars Developer
相关产品推荐
相关产品推荐

