Unity中OnTriggerEnter/OnCollisionEnter无响应,求解决
Unity触发器功能失效排查方案
以下是针对你遇到的触发器不工作问题的排查方向,结合你的代码和场景设置逐一分析:
1. 物理移动方式错误(代码核心问题)
你的代码中直接通过transform.localPosition修改Agent位置,这种方式会绕过Unity物理引擎的检测逻辑,导致触发器事件无法被正确触发。必须通过Rigidbody组件控制物体移动,修改后的完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.MLAgents; using Unity.MLAgents.Actuators; using Unity.MLAgents.Sensors; public class MoveAgent : Agent { [SerializeField] private Transform targetTransform; // 添加Rigidbody引用 [SerializeField] private Rigidbody agentRb; public override void OnEpisodeBegin(){ transform.position = new Vector3(42.59956f, 18.9153f, 144.7489f); // 重置刚体速度,避免残留速度影响 agentRb.velocity = Vector3.zero; } public override void CollectObservations(VectorSensor sensor){ sensor.AddObservation(transform.position); sensor.AddObservation(targetTransform.position); } public override void OnActionReceived(ActionBuffers actions){ float moveX = actions.ContinuousActions[0]; float moveZ = actions.ContinuousActions[1]; float moveSpeed = 2f; // 改用Rigidbody控制移动,确保物理引擎能检测碰撞/触发器 Vector3 moveDir = new Vector3(moveX, 0, moveZ).normalized; agentRb.MovePosition(agentRb.position + moveDir * moveSpeed * Time.deltaTime); } public override void Heuristic(in ActionBuffers actionsOut){ ActionSegment<float> continuousActions = actionsOut.ContinuousActions; continuousActions[0] = Input.GetAxisRaw("Horizontal"); continuousActions[1] = Input.GetAxisRaw("Vertical"); } private void OnCollisionEnter(Collision collision){ Debug.Log("CollisionEnter"); } private void OnTriggerEnter(Collider other){ Debug.Log("Trigger!"); if (other.TryGetComponent<Goal>(out Goal goal)){ SetReward(+1f); EndEpisode(); } if (other.TryGetComponent<Wall>(out Wall wall)){ SetReward(-1f); EndEpisode(); } } }
2. Rigidbody设置检查
- 确保Agent物体上的Rigidbody未勾选Is Kinematic,运动学刚体不会参与物理碰撞/触发器检测(除非与非运动学刚体交互,但你的场景中是Agent触发触发器,所以Agent的Rigidbody必须是非运动学状态)。
- 无需强制开启
Use Gravity,但即使关闭,只要是非运动学状态就不影响触发器检测。
3. 碰撞体与Layer设置
- 检查Agent和Trigger物体的碰撞体是否处于启用状态(Collider组件的Enabled勾选),且碰撞体的范围、位置正确,确保两者能发生重叠。
- 打开
Edit -> Project Settings -> Physics,查看Layer Collision Matrix,确认Agent所在的Layer与Trigger所在的Layer是互相勾选允许碰撞的状态,否则物理引擎会忽略两者的交互。
4. 物体激活状态与组件挂载
- 确认Agent和Trigger物体都处于激活状态(SetActive(true)),禁用状态的物体不会触发任何物理事件。
- 确认Trigger物体上正确挂载了
Goal或Wall组件,否则TryGetComponent会返回false,导致后续奖励逻辑不执行。
内容的提问来源于stack exchange,提问作者smitkims
相关产品推荐
相关产品推荐

