触发器的主要用法:

void OnTriggerEnter()
void OnTriggerEnter(Collider other) { if (other.gameObject.tag =="A")
//如果它触发的物体的tag叫A { Debug.Log("ontriggerA"); } else if (other.gameObject.tag ==
"B")//如果它触发的物体的tag叫B { Debug.Log("ontriggerB"); } }
首先我们先打开unity

此处使用的是easytouch插件控制人物移动,也可以用其他方法

首先设置墙(wall)和box的tag

   

box和wall都需要选中is Trigger,如果没有box Collider需要手动添加

注:此处的collider为box形式的长方体可用,如果触发器为别的形状需要修改。

人物身上必须要同时拥有Rigidbody和Collider

将以下代码挂载到人物身上,用debug测试下是否能够触发;
void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "wall")
//如果它触发的物体的tag叫wall { Debug.Log("TriggerWall"); } else if (other.gameObject.tag
== "box")//如果它触发的物体的tag叫box { Debug.Log("Triggerbox"); } }
由debug所见,可以正常运行

此时的代码就可以进行很多用处了

触发物体显示界面:

如果我想要人物触发box的时候显示这个界面,那么就可以这么写:

using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ontrigger : MonoBehaviour { public GameObject UImsg; void Start()
{ UImsg.SetActive(false); //不显示UImsg界面 } void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "wall") //如果它触发的物体的tag叫wall {
Debug.Log("TriggerWall"); } else if (other.gameObject.tag ==
"box")//如果它触发的物体的tag叫box { Debug.Log("Triggerbox"); UImsg.SetActive(true);
//显示UImsg界面 } } }

完成

如有问题可以在下方留言,谢谢!!

制作不易,求个一键三连QwQ~~

 

技术
今日推荐
PPT
阅读数 119
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信