unity 2D notes -- Elementary

· · 个人记录

unity 2D notes -- Elementary

1.unity基本操作

移动界面:Alt+鼠标右键
移动物体:使用Move Tool或按键W
旋转物体:使用Rotate Tool或按键E
改变大小:使用Scale Tool或按键R,或使用Rect Tool或按键T
复制:Ctrl+D
重命名:F2

PS:Toggle Tool Handle Rotation有两种模式:Global和Local。
Global - 旋转时红绿箭头不会随物体旋转
Local - 旋转时红绿箭头随物体旋转

2.unity图像

在Transform中:
position指涉物体(GameObject)的坐标。由于这里是2D,z坐标一般不用考虑。
rotation指涉GameObject的旋转
scale指涉GameObject的缩放。当scale设为负值时,可以产生某些镜像效果

3.unity图层

如上图红圈所示,有2种改变图层的方式。

(1)Sorting Layer

1 点击绿圈处的Layer --> Add Layer... --> Sorting Layers,点击“+”号创建新图层。Layer数字越大,图层层数越高。
2 修改红圈里的Sorting Layer即可。

(2)Order in Layer

在同一个Sorting Layer中,Order in Layer越大,图层层数越高。

Sorting Layer是主要关键字,Order in Layer是次要关键字。

4.Unity代码

Unity的代码称为script,可以理解为一种组件component),置于GameObject上,对特定的物体起作用。
比如下面的Driver.cs作为script组件至于Cruisy McDrive上:

unity代码示例:

PrintToConsole.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PrintToConsole : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

1.using类似c++中的include头文件。
2.注意到,class名称即为代码文件名。
3.Start和Update是unity代码的两个基本函数。Start在物体生成时执行一次,而Update每隔一小段时间执行一次。

5.Debug.Log()

Debug.Log()能将文字输出在console里,是调试的有力工具。这些文字不会出现在game view中。 比如在Start函数中加入以下代码:

void Start()
{
    Debug.Log("I'm printing to the console.");
}

在console中会显示如下结果:

PS:点击clear,即可清除所有消息;点击collapse,即可合并相同信息。

6.[SerializeField]

添加SerializeField后,这个变量就能在inspector中编辑,不必跑到代码中修改。

代码示例:

[SerializeField] float moveSpeed = 0.01f; //unity的小数一定要在末尾加f

实现效果如下:

在inspector中修改,不会改变代码中moveSpeed的初始值。

PS:unity中的变量首字母必须小写,且若存在大写字母,显示时会自动隔开,就像上图的moveSpeed。

7.[Header()]

Header能帮助归类在inspector中的变量。

代码示例:

[Header("Move")]
[SerializeField] float moveSpeed = 0.01f;
[Header("Steer")]
[SerializeField] float steerSpeed = 0.1f;

实现效果如下:

8.数学函数

Random.Range(a,b); //取一个范围在[a,b]内的随机数
Mathf.RoundToInt(a); //将a保留整数