Unity 3D Timer脚本报CS0117错误:PlayerCarController无accelarationForce定义
Unity 3D倒计时Timer脚本CS0117错误解决
你的两处CS0117错误由以下两个问题共同导致:
变量名拼写错误
PlayerCarController中定义的变量是accelerationForce,但Timer脚本里错误写成了accelarationForce(缺少字母e),这是编译器找不到该变量的直接原因。实例变量访问方式错误
accelerationForce是实例变量,你却试图用类名PlayerCarController直接访问,正确的方式是通过你已经声明的playerCarController实例对象来操作。
修正后的Timer脚本关键代码(Update方法部分)
void Update() { if(countDownTimer > 1) { playerCarController.accelerationForce = 0f; OpponentCar.movingSpeed = 0f; OpponentCar1.movingSpeed = 0f; OpponentCar2.movingSpeed = 0f; OpponentCar3.movingSpeed = 0f; OpponentCar4.movingSpeed = 0f; } else if(countDownTimer == 0) { playerCarController.accelerationForce = 300f; OpponentCar.movingSpeed = 12f; OpponentCar1.movingSpeed = 13f; OpponentCar2.movingSpeed = 14f; OpponentCar3.movingSpeed = 9f; OpponentCar4.movingSpeed = 8f; } }
额外注意事项
- 修正后,需要在Unity Inspector面板中,将挂载了
PlayerCarController脚本的玩家车对象,拖到Timer组件的playerCarController字段上,避免运行时出现空引用异常。 - 建议在访问实例变量前添加空值判断,比如:
if(playerCarController != null) { playerCarController.accelerationForce = 0f; }
内容的提问来源于stack exchange,提问作者Davinci
相关产品推荐
相关产品推荐

