You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity无尽跑酷教程障碍物碰撞玩家后不消失问题排查

问题修复方案

核心代码错误(首要修复项)

C#为大小写敏感语言,Unity的系统生命周期函数有固定命名规范,你当前Obstacle类中定义的碰撞触发函数名首字母为小写onTriggerEnter2D,Unity无法识别该函数,导致碰撞逻辑完全不执行,障碍物自然不会销毁。
将函数名修改为首字母大写的OnTriggerEnter2D即可,修正后的完整代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Obstacle : MonoBehaviour
{
    public int damage = 1;
    public float speed;

    private void Update()
    {
        transform.Translate(Vector2.left * speed * Time.deltaTime);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("rocket"))
        {
            other.GetComponent<rocket>().health -= damage;
            Debug.Log(other.GetComponent<rocket>().health);
            Destroy(gameObject);
        }
    }
}

其他可能导致问题的配置项(代码修正后仍不生效时排查)

  • 碰撞体配置检查:
    • 障碍物对象的Collider2D组件必须勾选「Is Trigger」选项
    • 玩家火箭对象必须挂载非触发器类型的Collider2D组件
    • 两个对象中至少有一个挂载Rigidbody2D组件(2D碰撞检测要求必须至少一方携带刚体)
  • 标签配置检查:玩家火箭对象的Tag必须设置为完全匹配的rocket字符串,大小写不能有出入
  • 组件挂载检查:确保Obstacle脚本正确挂载到了障碍物对象上,rocket脚本正确挂载到了玩家对象上

内容的提问来源于stack exchange,提问作者Linedol trainer channel gammin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:36:03