3d作业(二)
游戏对象和资源的区别和联系
游戏对象(GameObjects)
GameOjects是一个Unity的内建类,它是承载各种游戏控件的盒子。游戏中的各种元素赛车游戏中的小车、马里奥中移动的角色、灯光都是游戏对象的子类,继承并添加特定的功能已实现游戏特性。
资源(Assets)
游戏对象实现特性需要用到的各种代码、颜色。
区别
游戏对象可以单独存在与场景中,而资源必须要应用到游戏对象中才能发挥作用
联系
资源可以作为一种特性(如移动轨迹、颜色)等作用到一个或多个游戏对象中
也可以作为模板(如已经设计好的桌椅组合)实例化在游戏场景中
游戏案例中的资源和对象组织的结构
案例:Unity Royale
资源
可以看到资源一般包括效果、脚本等一些预设文件。
对象组织
对象组织一般包括游戏的角色(目标)、灯光等游戏对象。
验证 MonoBehaviour 基本行为或事件触发的条件
编写代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonoBehaviorTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log("Start!");
}
// Update is called once per frame
void Update()
{
Debug.Log("Update!");
}
void Awake(){
Debug.Log("Awake!");
}
void FixedUpdate(){
Debug.Log("FixedUpdate!");
}
void LateUpdate() {
Debug.Log("LateUpdate!");
}
void OnGUI(){
Debug.Log("OnGUI!");
}
void OnDisabled() {
Debug.Log("OnDisabled!");
}
void OnEnabled() {
Debug.Log("OnEnabled!");
}
}
函数 | 基本行为或触发条件 |
---|---|
Start |
在所有Update调用之前调用 |
Update |
在渲染每一帧时调用 |
Awake |
实例被载入时调用 |
FixedUpdate |
在固定的时间频率调用 |
LateUpdate |
在渲染每一帧时所有Update处理完后调用 |
OnGUI |
渲染GUI和处理GUI消息时调用 |
OnDisabled |
对象禁用或者取消激活的时候调用 |
OnEnabled |
对象启用或者激活的时候调用 |
查找脚本手册,了解 GameObject,Transform,Component 对象
-
分别翻译官方对三个对象的描述
GameObject
Unity’s GameObject class is used to represent anything which can exist in a Scene.
GameObject
用于表示场景中可能存在的任何内容
Transform
Position, rotation and scale of an object.
Transform
是对象的位置、旋转和缩放。
ComponentBase class for everything attached to GameObjects.
Component
是附加到GameObjects的所有内容的基类。
- 描述下图中table对象(实体)的属性、table的Transform的属性、table的部件
table的属性
table的Transform的属性
table的部件
Transform, Cube, Box Collider, Mesh Renderer
- 用UML图描述三者的关系(请使用UMLet14.1.1stand-alone版本出图)
资源预设(Prefabs)与对象克隆(clone)
-
预设(Prefabs)有什么好处?
预设是组件的集合体 , 预制物体可以实例化成游戏对象。预设相当于已经设计好的模板,可以方便用户批量设置游戏实例。
-
预设与对象克隆(clone or copy or Instantiate of Unity Object)关系?
预设和克隆都可以作用到多个游戏对象中,使其拥有相同的特性。
预设发生改变,作用的每一个实例也发生相应的改变,而克隆的对象之间不相互影响。
-
制作table预制,写一段代码将table预制资源实例化成游戏对象
完成table预制
拖到场景中
新建C# script,编写代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrefabsTest : MonoBehaviour
{
public Transform table;
// Start is called before the first frame update
void Start()
{
GameObject new_table = Instantiate<Transform> (table, this.transform).gameObject;
new_table.transform.position = new Vector3(1, 3, 0);
}
// Update is called once per frame
void Update()
{
}
}
执行结果