按键的获取
获取用户操作信息,需要 Inpu t类。
写在Update里,每帧都执行。
来看看代码和代码注释。
备注,以下 Input 类中的函数都返回 bool 值。
using UnityEngine;
using System.Collections;
public class INA : MonoBehaviour {
void Start () {
}
void Update () {
//每一帧都监听用户操作
bool b = Input.GetKeyDown(KeyCode.W);//按下时
if(b)
{
print("往前走");
}
if(Input.GetKeyDown(KeyCode.S))
{
print("往后走");
}
if(Input.GetKey(KeyCode.A))//只要按的时候(可以理解为持续按下的时候)
{
print("往左走");
}
if(Input.GetKeyUp(KeyCode.D))//键盘弹起时
{
Debug.Log("往右走");//等于 print("往右走");
}
if(Input.GetKeyDown(KeyCode.Alpha1))
{
Debug.Log("切换为主武器//使用血瓶");
}
//Input.GetMouseButtonDown()监听鼠标按键按下。Down改为Up等等。
//函数输入值为 0 监听鼠标左键。 1 为右键。 2为鼠标中键。
if (Input.GetMouseButtonDown(0))
{
print("按下了鼠标左键");
}
}
}
Inspector
Tag 值的操作。标签对对象统一操作。(如全屏秒杀的技能,所有Tag为enemy的血量减少。)
layer 层级。(如不显示屋顶层级,摄像机透过屋顶显示室内。)
GameObject(gameObject)
10个常用GameObject操作。
Name,Tag,ActiveSelf,SetActive(),GetComponent<T>(),AddComponent<T>(),Destroy(),FindGameObjectwithTag(),FIndGameObjectswithTag()。
using UnityEngine;
using System.Collections;
public class INabc : MonoBehaviour {
void Start () {
gameObject.name = "游戏开发";//对象的名字
gameObject.tag = "enmery";//对象的tag标签
print(gameObject.activeSelf);//打印激活状态
// GO a = gameObject.GetComponent<GO>();获取组件。
// a.name="1234";//获取组件后操作组件的属性。
// printf(a.name);
Light k=gameObject.AddComponent<Light>();//添加灯光组件
GameObject s = GameObject.FindGameObjectWithTag("Player");//这里的 Game 首字母要大写。获取游戏中 tag 为 Player 的对象。
print(s.transform.position.x);
//GameObject ss = GameObject.FindWithTag("Player");等价于上面获取tag。
//print(ss.transform.position.x);
//除了通过tag,也可以可以通过名字获取gameObject
//GameObject sss=GameObject.Find("Main Camera");//获取名字叫 Main Camera 的游戏对象
//print(sss.transform.position.x);
}
void Update () {
if(Input.GetMouseButtonDown(0))
{
gameObject.SetActive(true);//激活对象。
print(gameObject.activeSelf);//打印激活状态。
}
if (Input.GetMouseButtonDown(1))
{
gameObject.SetActive(false);//取消对象的激活。
print(gameObject.activeSelf);//打印激活状态。
}
if(Input.GetKeyDown(KeyCode.R))
{
GameObject.Destroy(gameObject);//按下 R 销毁游戏对象。
// GameObject.Destroy(gameobject,3f);//按下 R ,等3秒后,销毁游戏对象。
}
if (Input.GetKeyDown(KeyCode.T))
{
GameObject.Destroy(gameObject,2f);//按下 T 等3秒 销毁游戏对象。
}
if(Input.GetKeyDown(KeyCode.Y))
{
GameObject[] ssss = GameObject.FindGameObjectsWithTag("Player");//获取数组,所有Tag为Player的数组。
}
}
}