Speed Boost增益道具代码异常:道具未销毁且加速效果不生效
问题分析与修复方案
核心代码问题
你写的两段逻辑代码(加速计时、玩家移动)没有放在Unity的生命周期函数里,直接暴露在类作用域下,这部分代码永远不会被执行。同时,OnTriggerEnter的触发还需要满足物理条件才能生效。
修复后的完整代码
private float speed; private float boostTimer; private bool boosting; private bool moving; void Start() { moving = false; transform.Translate(1, 1, 1); speed = 5; boostTimer = 0; } void Update() { // 处理加速计时逻辑 if (boosting) { boostTimer += Time.deltaTime; if (boostTimer >= 3) { speed = 5; boostTimer = 0; boosting = false; } } // 处理玩家移动逻辑 if (moving) { this.transform.Translate(new Vector3(Time.deltaTime * speed, 0, 0)); } } void OnTriggerEnter(Collider other) { if(other.CompareTag("SpeedBoost")) // 推荐用CompareTag,比直接判断标签性能更优 { boosting = true; speed = 10; Destroy(other.gameObject); } }
额外检查项
- 玩家对象:必须带有Collider(需勾选
IsTrigger)和Rigidbody(如果是玩家主动移动,可勾选Kinematic避免受物理引擎影响) - 加速道具对象:必须带有Collider(需勾选
IsTrigger),且标签正确设置为SpeedBoost - 确保两个对象的Layer没有在Physics设置中被排除碰撞检测
内容的提问来源于stack exchange,提问作者stratutrav
相关产品推荐
相关产品推荐

