GameObject是游戏场景中真实存在的,而且有位置的一个物件
Component附属于GameObject,控制GameObject的各种属性
GameObject是由Component组合成的,Component的生命周期和GameObject息息相关。调用此GameObject的Destroy方法,它的子对象和对应的所有Component都会被销毁,但也可以一次只销毁一个Component
常见的Component:
Component | 作用 |
---|---|
RigidBody 刚体 | 使物体能在物理控制下运动 |
Collider 碰撞器 | 和RigidBody刚体一起使碰撞发生,没有Collider,两个碰撞的刚体会相互穿透 |
Renderer 渲染器 | 使物体显示在屏幕上 |
AudioSource 音频源 | 使物体在scence场景播放音频 |
Animation 动画 | |
Animator 动画控制器 |
同时所有脚本都是组件,因此都能附到游戏对象上
常用的组件可以通过简单的成员变量获取
附在游戏对象上的组件或脚本可以通过GetComponent获取
using UnityEngine; using System.Collections; public class example : MonoBehaviour { void Awake() { transform.Translate(0, 1, 0); GetComponent<Transform>().Translate(0, 1, 0); } }
在InputManager可以创建虚拟轴和按钮,并终端用户可以在屏幕配置对话框配置键盘输入。
如果想添加新的虚拟轴,选择菜单Edit->Project Settings->Input menu。这里可以改变每个轴的设置。即可进入Input Manager的配置界面。
在脚本中,所有虚拟轴通过它们的名字(name)来访问
每个项目创建后,都有下面的默认输入轴:
Time
Time类是Unity中的一个全局变量,它记载了和游戏相关的时间,帧数等数据
Time类包含一个非常重要的变量叫deltaTime.这个变量包含从上次调用Update 或FixedUpdate到现在的时间(根据你是放在Update函数还是FixedUpdate函数中)(Update每帧调用一次)
例:使物体在一个匀速的速度下旋转,不依赖帧的速率
using UnityEngine; using System.Collections; public class example : MonoBehaviour { void Update() { transform.Rotate(0, 5 * Time.deltaTime, 0); } }
Physics和Transform
Physics类是一个工具函数类,它主要提供了Linecast和Raycast两种射线投射方式。
来判断这个投射有没有和某个Collider发生了碰撞。
using UnityEngine; using System.Collections; public class Example : MonoBehaviour { void Update() { // 使用Raycast Vector3 fwd = transform.TransformDirection(Vector3.forward); if (Physics.Raycast(transform.position, fwd, 10)) print("There is something in front of the object!"); // 使用Linecast Transform target; if (!Physics.Linecast(transform.position, target.position)) ProcessData.AndDoSomeCalculations(); } }
在Physics这个模块包含三个最重要的Component:RigidBody,Collision,Joint
GameObject是游戏场景中真实存在的,而且有位置的一个物件
而控制GameObject则需要脚本组件
MonoBehaviour 是 Unity 中所有脚本的基类
MonoBehaviour is the base class from which every Unity script derives.
MonoBehaviour生命周期
在游戏里经常出现需要检测敌人和我方距离的问题,这时如果要寻找所有的敌人,显然要消耗的运算量太大了,所以最好的办法是将攻击范围使用Collider表示,然后将Collider的isTrigger设置为True。最后使用OnTriggerEnter来做攻击范围内的距离检测,这样会极大提升程序性能。
脚本的基本结构
using System.Collections; using System.Collections.Generic; using UnityEngine; using MyGame; //3引用命名空间 public class player : MonoBehaviour { // Use this for initialization void Start () { GameData data; //4才可以使用 } // Update is called once per frame void Update () { } } namespace MyGame { //1定义命名空间 class GameData { //2属于MyGame下的类 } }
Time,Input,Physics都是Unity中的全局变量
GameObject是游戏中的基本物件,是由Component组合而成的,GameObject本身必须有Transform的Component
GameObject是游戏场景中真实存在,而且有位置的一个物件