一、碰撞交互事件OnTriggerEnter
1、在场景中添加两个几何体(例如Cube和Sphere)

2、添加Rigidbody(刚体)component
点击Cube(正方体)对象,在面板找到这个按钮,添加component

搜索Rigidbody

默认状态下collider(碰撞)是被开启的。

3、创建C#脚本,增加OnTriggerEnter事件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class e : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("碰撞发生啦!");
var renderer = GetComponent<Renderer>();
renderer.material.SetColor("_Color", Color.blue);
}
}
4、将shpere(球体)设置为触发器,不需要添加刚体和代码。

5、将正方体摆放在球体上方,自由降落,可以看到穿过球体的过程中执行了碰撞交互事件(变蓝色)

二、碰撞交互事件OnCollisionEnter
1、将Is Trigger取消勾选。
2、将代码修改为:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class e : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
Debug.Log("碰撞发生啦!");
var renderer = GetComponent<Renderer>();
renderer.material.SetColor("_Color", Color.blue);
}
}
三、总结
(1)两个GameObject中,被动碰撞体必须包含一个 Collider(碰撞),一个Rigidbody(刚体),被动碰撞体上需要启用isTrigger(触发器)。刚体不能勾选IsKinematic。
(2)如果两个GameObject都有Collider都开启isTrigger时,或者两个GameObject都没有Rigidbody组件时,碰撞将不发生。
(3)当触发OnTriggerEnter方法,OnCollisionEnter则不会被执行。
官方:Collider.OnTriggerEnter(Collider)
官方:Collider.OnCollisionEnter(Collision)


![[附源码]Python计算机毕业设计SSM基于Java的运动健身平台(程序+LW)](https://img-blog.csdnimg.cn/380bd1fe78784cf5b6d50e82edbe675d.png)





![[附源码]Python计算机毕业设计高校社团管理平台Django(程序+LW)](https://img-blog.csdnimg.cn/b5a00ac25a554d5e8ec9e6a850bf4387.png)







![[附源码]Nodejs计算机毕业设计基于的二手房交易系统Express(程序+LW)](https://img-blog.csdnimg.cn/bf8b34abeef2437c97080ac0cdb08f96.png)


