You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Unity 2D中满足全部条件但OnTriggerEnter仍未触发的问题

Unity 2D中满足全部条件但OnTriggerEnter仍未触发的问题

嘿,我看你碰到了Unity 2D触发器不生效的问题,咱们先揪出最可能的原因——你用错了触发器方法!

你当前代码里写的是3D物理系统的OnTriggerEnter(Collider),但你的场景里用的全是2D组件(Rigidbody2D、BoxCollider2D),2D物理系统对应的触发器方法是OnTriggerEnter2D(Collider2D other),参数也要换成2D的Collider2D类型。

给你修正后的代码:

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

public class CollisionScript : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
        Debug.Log("Triggered with " + other.gameObject.name);
    }
}

如果换了方法还是不行,咱们再排查几个常见的坑:

  • Rigidbody2D设置问题:Unity 2D要求至少有一个碰撞物体的Rigidbody2D不是「Kinematic」(运动学)状态;如果两个都是Kinematic,那必须有一个物体是通过代码主动移动的(比如用Transform.position或者Rigidbody2D.MovePosition),静态的Kinematic物体之间不会触发触发器。
  • Layer碰撞矩阵:去「Edit > Project Settings > Physics 2D」里检查Layer Collision Matrix,确保你的两个物体所在的Layer是允许相互碰撞的,别不小心把对应层的碰撞给关了。
  • Collider重叠问题:在Scene视图里打开Gizmos显示,确认两个物体的BoxCollider2D在碰撞时真的有重叠部分,有时候Collider的大小或者位置没调好,看起来碰了实际没触发。
  • 物体/脚本激活状态:确保挂载脚本的物体是激活的(Active勾选),脚本本身也没有被禁用。

原问题描述:
I wrote this simple unity script that is supposed to write in console when it collides with something but it doesn't seem to work.

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

public class CollisionScript : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
Debug.Log("Triggered with " + other.gameObject.name);
}
}

I made sure that both the object that this script is assigned to and the object that this object is supposed to thouch have a RigidBody 2D and a Box Collider 2D and that their Box Colliders have "IsTrigger" activated.

备注:内容来源于stack exchange,提问作者Ivan Mishin

火山引擎 最新活动