键盘事件
按下事件:Input.GetKeyDown()
例如:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shsyhs : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
Debug.Log("您按下了“W”");
}
if (Input.GetKeyDown(KeyCode.S))
{
Debug.Log("您按下了“S”");
}
if (Input.GetKeyDown(KeyCode.D))
{
Debug.Log("您按下了“D”");
}
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("您按下了“A”");
}
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("您按下了“空格”");
}
}
}
擡起事件:Input.GetKeyUp() (用法和按下时间差不多,省略)
长按事件:Input.GetKey()
下面是一个检测连续按下空格次数的例子:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shsyhs : MonoBehaviour
{
int count = 0;
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
count++;
}
if (Input.GetKeyUp(KeyCode.Space))
{
Debug.Log("您连续按"+count+"次空格");
count = 0;
}
}
}
结果:
任意键事件
Input.anyKeyDown
Input.anyKey
鼠标事件
按下事件
Input.GetMouseButtonDown()方法:检测鼠标哪个按键被按下,返回参数是0(左键),1(中建),2(右键)
Input.mousePosition(得到鼠标当前座标)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shsyhs : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("您按下鼠标左键,座标为"+Input.mousePosition);
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("您按下鼠标中键,座标为" + Input.mousePosition);
}
if (Input.GetMouseButtonDown(2))
{
Debug.Log("您按下鼠标右键,座标为" + Input.mousePosition);
}
}
}
擡起事件:Input.GetMouseButtonUp()
对上述代码进行补充:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shsyhs : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("您按下鼠标左键,座标为"+Input.mousePosition);
}
if (Input.GetMouseButtonDown(1))
{
Debug.Log("您按下鼠标中键,座标为" + Input.mousePosition);
}
if (Input.GetMouseButtonDown(2))
{
Debug.Log("您按下鼠标右键,座标为" + Input.mousePosition);
}
if (Input.GetMouseButtonUp(0))
{
Debug.Log("您擡起鼠标左键,座标为" + Input.mousePosition);
}
if (Input.GetMouseButtonUp(1))
{
Debug.Log("您擡起鼠标中键,座标为" + Input.mousePosition);
}
if (Input.GetMouseButtonUp(2))
{
Debug.Log("您擡起鼠标右键,座标为" + Input.mousePosition);
}
}
}
运行结果:
注意:上述代码将中键和右键写反了,1是右键,2是中键。抱歉!!自己改一下就好了
长按事件:Input.GetMouseButton()
使用方法和键盘长按事件基本一致,略。