调用其它组件中成员
通过GameObject(游戏物体)。
Base class for all entities in Unity scenes。 是Unity场景里面所有实体的基类。
可以理解为两个类间的访问,定义一个超类用其中一个类实现。
默认的gameObject为当前组件。transform为变换,有常用属性position(Vector3三维向量)。
熟记transform下属性和方法作用。
transform.translate() 平移,给定vector3,给定坐标系'物体坐标系或者世界坐标系'。由于每秒执行60次,可以用Time.deltaTime(增量时间:以秒计算,完成最后一帧的时间)放慢。
让cube在n个点间转动:
using UnityEngine;
using System.Collections; public class TransformTest : MonoBehaviour { // Use this for initialization
public Transform[] point ;//n个点,在unity中控制长度和gameobject
public Transform nextPoint ;//下一个要运动到的点
public int index ;//当前位置,用于求下一个要运动到的点
void Start () {
index = ;
nextPoint = point[] ;
} // Update is called once per frame
void Update () {
if(Vector3.Distance(transform.position, nextPoint.transform.position)>0.1f){//transform默认为当前物体,同gameObject
transform.Translate(Vector3.Normalize(nextPoint.position-transform.position)**Time.deltaTime, Space.World) ;//normalize,向量标准化
//这里要用世界坐标系,用物体坐标系的话,在改变cube的Rotation后出错
}else{
index = (index+)%point.Length ;
nextPoint = point[index] ;
}
}
}
旋转,正角度为左手,负角度右手。transform.Rotate (new Vector3(0, -1, 0));
改变父物体的比例,子物体也会改变,比例不为1:1,移动父物体,子物体同样移动。(transform.parent,获取父物体的transform)
transform.position输出的是世界坐标系下的坐标位置,transform.localPosition为在父物体下物体坐标系的坐标位置。
定时重复调用可以使用InvokeRepeating函数实现, 启动0.5秒后每隔1秒执行一次 DoSomeThing 函数
void Start() {
InvokeRepeating("DoSomeThing", 0.5f, 1.0f);
}
监控键盘:
Input.GetKeyDown(KeyCode.W) KeyCode中包含键盘所有键位
Input.GetKeyUp(KeyCode.W)
Input.GetKey(KeyCode.W) 按下时一直执行
对三种不同的动作监控
// if(Input.GetKey(KeyCode.W)){
// transform.Translate(Vector3.forward) ;
// }
// if(Input.GetKey(KeyCode.S)){
// transform.Translate(-Vector3.forward) ;
// }
// if(Input.GetKey(KeyCode.A)){
// transform.Rotate(-Vector3.up);
// }
// if(Input.GetKey(KeyCode.D)){
// transform.Rotate(Vector3.up);
// }
等同 transform.Translate(new Vector3(, , Input.GetAxis("Vertical"))) ;
transform.Rotate(new Vector3(, Input.GetAxis("Horizontal"), )) ;//获取轴 edit/projectsetting/input
Time.timeScale 改变游戏运行速度,0为暂停游戏,暂停时update继续执行(FixedUpdate()下完全停止)。
用Time.timescale加速或者减速时,在FixedUpdate()下使用。
GameObject.tag 标签
GameObject.layer 层
都可自定义
GameObject.FindGameObjectsWithTag 返回GameObject[]
GameObject.FindGameObjectWithTag 返回GameObject
若在脚本AScript里想要获取BScript里的变量,先获取BScript所在GameObject的实例
例:
GameObject mainCarm = GameObject.FindGameObjectWithTag("MainCamera") ;
然后通过mainCarm找到BScript实例
BScript bScript = (BScript)mainCarm.GetComponent("BScript") ;
这样就可以使用BScript里的所有公共变量和方法。
GameObject.SendMessage("方法名"); 若本身调用,搜寻同级所有GameObject,若其他object调用,搜寻该object中的此方法