MonoBehaviour 类是一个基类,所有 Unity 脚本都默认派生自该类。当您从 Unity 的项目窗口创建一个 C# 脚本时,它会自动继承 MonoBehaviour,并为您提供模板脚本。请参阅创建和使用脚本以了解更多相关信息。
MonoBehaviour 类提供了框架,允许您将脚本附加到编辑器中的游戏对象,并提供诸如 Start 和 Update 等常用事件的挂钩。
For a complete reference of every member of the MonoBehaviour class, and its technical details, see the MonoBehaviour script reference.
When you select a script in the Project window, the Inspector displays some basic information about that script asset, including the name of the assembly it belongs to, and a preview of the contents of the script.
Note: Although the Inspector displays the contents of the script, you can’t edit the script in the Inspector window.
The script inspector also displays two buttons, Open and Execution Order.
The Open button opens the script in the currently configured External Script Editor (also known as an Integrated Development Environment, or IDE). The Open button performs the same function as double-clicking the script in the Project window. You can configure which external editor Unity uses to open your scripts in the External Tools section of the Preferences window.
The Execution Order button opens the Script Execution Order section of the Project Settings window, which allows you to alter the the order in which Unity executes your scripts.
If you define public Object fields that can be assigned in the Editor in your MonoBehaviour script, you can set up default references for these fields. The default reference fields are visible in the inspector when you select the script asset in the Project window.
In the example above, there are three public Audio Clip fields, without default references assigned. You could assign audio clips to each of the AudioClip default reference fields.
If you assign default references, they are applied when you add your MonoBehaviour as a component to a GameObject, or when you reset an existing instance of your MonoBehaviour on a GameObject to its default values.
Note: There is no ongoing link between the references on MonoBehaviour instances on GameObjects and the default references. This means if you change the default references, they are not automatically updated on existing GameObjects.
Other types of inspector-editable fields that do not inherit from UnityEngine.Object
(for example, public string or int fields) do not have default fields in the inspector. Instead, they take their default values from the script itself.
MonoBehaviour 类允许您启动、停止和管理协程,这是一种编写异步代码的方法,其中包括等待一定时间或某些操作完成,同时允许其他代码继续执行。
有关协程的更多信息,请参阅协程手册页和 StartCoroutine 方法脚本参考。
MonoBehaviour 类提供对大量事件消息的访问,允许您根据项目中当前发生的情况执行代码。下面是一些比较常见的例子。有关完整的列表,请参阅 MonoBehaviour 脚本参考页面 上的消息部分
Start
- 在游戏对象开始存在时(加载场景或实例化游戏对象时)调用。
Update
- 每帧都会被调用。
FixedUpdate
- 每个物理时间步进调用。
OnBecameVisible
和 OnBecameInvisible
- 当游戏对象的渲染器进入或离开摄像机的视图时调用。
OnCollisionEnter
和 OnTriggerEnter
- 在发生物理碰撞或触发时调用。
OnDestroy
- 在销毁游戏对象时调用。