Unity 脚本
- 文件名与类名必须一致;
- 写好的脚本必须附加到物体上才执行;
- 附加到游戏物体的脚本类必须从
MonoBehaviour
类继承。 Start()
和Update()
方法不需要的话就删掉,特别是
Update()
。
编译过程
源代码 -> CLS -> 中间语言 -> 机器码
如何修改 unity 中脚本模版
打开 unity 所在文件夹,我的本地路径如下:
Editor\Data\Resources\ScriptTemplates
对于 C# 脚本,修改 81- 开头的那个文件即可(用 visual studio 打开)。
脚本生命周期
Unity脚本从唤醒到销毁的过程,当满足某种条件Unity引擎自动调用的函数。也称必然事件、消息(Message)等。
本节课介绍三种:
MonoBehaviour.Awake()
Awake is called when the script instance is being loaded.MonoBehaviour.Start()
Start is called on the frame when a script is enabled just before any of the Update methods are called the first time.MonoBehaviour.OnEnable()
This function is called when the object becomes enabled and active.
注意Awake
和Start
的先后顺序,并可以加以利用:
Like the Awake function, Start is called exactly once in the lifetime of the script. However, Awake is called when the script object is initialised, regardless of whether or not the script is enabled. Start may not be called on the same frame as Awake if the script is not enabled at initialisation time.(如果需要判断当满足某种条件时执行此脚本,可以使用语句if (statement) this.enable = true;
)
The Awake function is called on all objects in the Scene before any object’s Start function is called. This fact is useful in cases where object A’s initialisation code needs to rely on object B’s already being initialised; B’s initialisation should be done in Awake, while A’s should be done in Start.
在编辑器中显示或隐藏成员
// 序列化字段 作用:在编辑器中显示私有变量
[SerializeField]
private int a = 100;
// 在编辑器中隐藏
[HideInInspector]
public int b;
// 设置修改范围
[Range(0, 100)]
public int c;