Version: 2023.1

ExecuteAlways

class in UnityEngine

切换到手册

描述

使脚本的实例在播放模式期间以及编辑时始终执行。

默认情况下,MonoBehaviours 仅在播放模式下并且仅当它们位于包含用户场景的主阶段中的游戏对象上时才执行。它们不会在编辑模式下执行,也不在预制件模式下编辑的对象上执行,即使此时在播放模式下也是如此。通过添加此属性,MonoBehaviour 的任何实例都将始终执行其回调函数。

You can use the [ExecuteAlways] attribute when you want your script to perform certain things as part of Editor tooling, which is not necessarily related to the Play logic that happens in built Players and in Play Mode. Sometimes the Play functionality of such a script is identical to its Edit Mode functionality, while other times they differ greatly.

使用此属性的 MonoBehaviour 必须确保它们在编辑模式下或者在对象不是游戏世界的一部分时不会运行可能导致对象被错误修改的播放逻辑。为达到此目的,可以使用 Application.IsPlaying,在其中,脚本可以传入自己的游戏对象以检查它是否是游戏世界的一部分。

如果 MonoBehaviour 在播放模式下运行播放逻辑并且无法检查其游戏对象是否是游戏世界的一部分,则在预制件模式下编辑的预制件可能会被仅用作游戏世界一部分的逻辑错误地修改和保存。

如果您的脚本使用静态变量或单例模式,则应确保属于游戏世界的脚本实例和不属于游戏世界的实例不会通过这些变量或单例意外地相互影响。

在不属于游戏世界的对象上,不会像其他情况那样不断地调用以下函数。 Update is only called when something in the Scene changed. OnGUI is called when the Game view receives a non-editor-only Event that it does not use (e.g., EventType.ScrollWheel) and does not forward to the Editor's keyboard shortcut system (e.g., EventType.KeyDown, EventType.KeyUp). Events forwarded to the Game view are enqueued and are not guaranteed to be processed immediately. OnRenderObject and the other rendering callback functions are called on every repaint of the Scene view or Game view. 另请参阅:Application.IsPlayingrunInEditModeEditorApplication.QueuePlayerLoopUpdate

using UnityEngine;

[ExecuteAlways] public class ExampleClass : MonoBehaviour { void Start() { if (Application.IsPlaying(gameObject)) { // Play logic } else { // Editor logic } } }