unity 输入与组件调用 – 笔记

发布于 2022-11-06  109 次阅读


15 输入

鼠标相关api
button values are 0 for left button, 1 for right button, 2 for the middle button. The return is true when the mouse button is pressed down, and false when released.
//按下事件
Input.GetMouseButtonDown(0);
//抬起事件
Input.GetMouseButtonUp(1);
//按住鼠标状态
Input.GetMouseButton(2);
//按下a键事件 小写
Input.GetKeyDown("a")
枚举 KeyCode.A

获取鼠标二维屏幕位置 摄像头中位置
Input.mousePosition
单位为像素,二维平面,左下角为原点(0,0)

Screen.width
Screen.height

获取实体在二维屏幕上的位置
Camera.main.WorldToScreenPoint(obj.transform.position);
可以判断实体是否在屏幕中,是否超出视野范围。

获取实体中的组件

AudioSource audioTest = this.GetComponent();
通过audioTest可以控制音频组件中的参数

引用其他物体组件
其组件必须为public

调用其他脚本方法
sendMessage利用反射,但是效率低下,所以基本很少看到有人用
第一种,被调用脚本函数为static类型,调用时直接用 脚本名.函数名()
//能调用public和private类型函数
第二种,GameObject.Find("脚本所在的物体的名字").SendMessage("函数名");
//可以添加参数
第三种,GameObject.Find("Main Camera").GetComponent().SendMessage("SetWipeOutNum",null);
//只能调用public类型函数
第四种,GameObject.Find("脚本所在的物体的名字").GetComponent<脚本名>().函数名();


啦啦啦!