文档

Unity 引擎

Unity 引擎

自定义 Player Loop

自定义 Player Loop可Change Unity 在Loop的每个迭代中更新系统的Order。
阅读时间8 分钟最后更新于 5 天前

Unity 运行时Applications程序在称为 Player Loop的ContinuousLoop中运行。在 Player Loop 的每个迭代期间,Unity Calls 都会调用各种系统来执行渲染、Physics 模拟和输入处理等任务。
在播放PlayerLoop期间已更新的各种系统和子系统以定义的默认Order调用。您可以使用
PlayerLoop
API 中的 Static 方法查看和自定义此 Order。您可以检索默认或当前的 Player Loop 并插入您自己的自定义 Player Loop 系统,或者移除、重新排序或替换现有系统。
可能需要自定义 Player Loop 有几个原因:
  • 在自定义更新管理器中创建自己的 Managed 更新可以替代 Unity 的原生事件函数。有关更多信息,请参阅 Unity 博客 ON 10000 Update Calls。
  • 您可能希望针对指定的平台优化 Player Loop,例如删除移动端端游戏的Physics、AI 和 XR 更新。
  • 您可能希望在编辑模式或播放模式下创建更新 Loop 的可视化以帮助进行调试。

访问 Player Loop

Player Loop 由一系列嵌套的 Player Loop 系统组成,每个系统都是一个
PlayerLoopSystem
结构。根或最外层播放PlayerLoopSystem表示完整的播放PlayerLoop,Other播放PlayerLoop系统嵌套在播放器循环下。
在这种情况下,Player Loop System 只是 Player Loop 期间需要更新的任何内容的抽象表示。默认系统是原生 Unity 系统(例如 音频 和 输入)的表示形式,但您也可以从 C# 代码创建自己的自定义系统。
要访问 Unity 的默认 Player Loop,请使用
PlayerLoop.GetDefaultPlayerLoop
。要访问当前有效的 Player Loop,请使用
PlayerLoop.GetCurrentPlayerLoop
。默认和当前 Player Loop 将相同,除非使用
PlayerLoop.SetPlayerLoop
Apply 新建自定义 Player Loop。
Player Loop 中的每个系统都有一个标识它的
PlayerLoopSystem.type
属性。您可以递归迭代 Player Loop System 结构,并打印每个
type
属性的
Name
以在控制台中显示 Player Loop 结构。您还可以使用
type
属性(如以下示例所示)来标识要添加、移除或替换的 Player Loop 子系统。
UnityEngine.PlayerLoop
命名空间中提供了默认系统的有效类型。
API 参考
PlayerLoop.GetDefaultPlayerLoop
包括如何检索默认 Player Loop、迭代嵌套的 Player Loop 系统并打印其
type
Properties
Name
的示例。代码产生以下控制台输出:
根节点 TimeUpdate WaitForLastPresentationAndUpdateTime 初始化 ProfilerStartFrame UpdateCameraMotionVectors DirectorSampleTime AsyncUploadTimeSlicedUpdate SynchronizeInputs SynchronizeState XREarlyUpdate EarlyUpdate PollPlayerConnection GpuTimestamp AnalyticsCoreStatsUpdate UnityWebRequestUpdate ExecuteMainThreadJobs ProcessMouseInWindow ClearIntermediateRenderers ClearLines PresentBeforeUpdate ResetFrameStatsAfterPresent UpdateAsyncInstantiate UpdateAsyncReadbackManager UpdateStreamingManager UpdateTextureStreamingManager UpdatePreloading UpdateContentLoading RendererNotifyInvisible PlayerCleanupCachedData UpdateMainGameViewRect UpdateCanvasRectTransform XRUpdate UpdateInputManager ProcessRemoteInput ScriptRunDelayedStartupFrame UpdateKinect DeliverIosPlatformEvents ARCoreUpdate DispatchEventQueueEvents Physics2DEarlyUpdate PhysicsResetInterpolatedTransformPosition SpriteAtlasManagerUpdate PerformanceAnalyticsUpdate FixedUpdate ClearLines NewInputFixedUpdate DirectorFixedSampleTime AudioFixedUpdate ScriptRunBehaviourFixedUpdate DirectorFixedUpdate LegacyFixedAnimationUpdate XRFixedUpdate PhysicsFixedUpdate Physics2DFixedUpdate PhysicsClothFixedUpdate DirectorFixedUpdatePostPhysics ScriptRunDelayedFixedFrameRate PreUpdate PhysicsUpdate Physics2DUpdate PhysicsClothUpdate CheckTexFieldInput IMGUISendQueuedEvents NewInputUpdate InputForUIUpdate SendMouseEvents AIUpdate WindUpdate UpdateVideo --update ScriptRunBehaviourUpdate ScriptRunDelayedDynamicFrameRate ScriptRunDelayedTasks DirectorUpdate PreLateUpdate AIUpdatePostScript DirectorUpdateAnimationBegin LegacyAnimationUpdate DirectorUpdateAnimationEnd DirectorDeferredEvaluate AccessibilityUpdate UIElementsUpdatePanels EndGraphicsJobsAfterScriptUpdate ConstraintManagerUpdate ParticleSystemBeginUpdateAll Physics2DLateUpdate PhysicsLateUpdate ScriptRunBehaviourLateUpdate PostLateUpdate PlayerSendFrameStarted DirectorLateUpdate ScriptRunDelayedDynamicFrameRate PhysicsSkinnedClothBeginUpdate UpdateRectTransform PlayerUpdateCanvases UIElementsRepaintPanels UpdateAudio VFXUpdate ParticleSystemEndUpdateAll EndGraphicsJobsAfterScriptLateUpdate UpdateCustomRenderTextures XRPostLateUpdate UpdateAllRenderers UpdateLightProbeProxyVolumes EnlightenRuntimeUpdate UpdateAllSkinnedMeshes ProcessWebSendMessages SortingGroupsUpdate UpdateVideoTextures UpdateVideo DirectorRenderImage PlayerEmitCanvasGeometry UIElementsRenderBatchModeOffscreen PhysicsSkinnedClothFinishUpdate FinishFrameRendering BatchModeUpdate PlayerSendFrameComplete UpdateCaptureScreenshot PresentAfterDraw ClearImmediateRenderers PlayerSendFramePostPresent UpdateResolution InputEndFrame TriggerEndOfFrameCallbacks GUIClearEvents ShaderHandleErrors ResetInputAxis ThreadedLoadingDebug ProfilerSynchronizeStats MemoryFrameMaintenance ExecuteGameCenterCallbacks XRPreEndFrame ProfilerEndFrame GraphicsWarmupPreloadedShaders ObjectDispatcherPostLateUpdate

将自定义更新插入到默认PlayerLoop中

自定义播放PlayerLoop的建议和最低风险方法是将自定义定义PlayerLoopSystem插入到默认播放PlayerLoop中。这样,您可以添加自己的自定义更新逻辑,而不会中断 Unity 的Any内置系统。
PlayerLoop.SetPlayerLoop
API 参考中的代码示例展示了如何在指定点将自定义 Player Loop System 插入到默认 Player Loop 中。在这种情况下,
CustomUpdate
方法的行为在
InsertSystem
类中定义。但以下小修改可以使
CustomUpdate
成为 MonoBehaviour 脚本可以订阅的事件并为其提供自己的更新逻辑:
  • 将事件声明为
    InsertSystem
    类的 public Static Field:
public static event Action AddCustomUpdate;
  • 修改
    CustomUpdate
    方法的定义以调用此事件:
private static void CustomUpdate() => AddCustomUpdate?.Invoke();
然后,可从Any MonoBehaviour 脚本本订阅自定义更新,如下所示:
using UnityEngine;public class CustomUpdateFromEvent :MonoBehaviour{ private void OnEnable() { InsertSystem.AddCustomUpdate += MyCustomUpdate; } private void 更新() { Debug.Log("Update"); } private void LateUpdate() { Debug.Log("Late Update"); } private void OnDisable() { InsertSystem.AddCustomUpdate -= MyCustomUpdate; } private void MyCustomUpdate() { Debug.Log("Custom update from an event that your MonoBehaviour scripts can subscribe to."); }}
注意
作为参数通道到
PlayerLoop.SetPlayerLoop
的 Player Loop System 会覆盖当前的 Player Loop。因此,make通道此方法的AnyLoop都包含要保持的All系统,包括不替换的系统。如果从头开始创建新建的播放PlayerLoopSystem,则必须显式将想要保持的All系统添加到新建Loop中。

在 Player Loop中替换默认Systemstem

以下示例将 Player Loop中的默认System替换为自定义定义更新。该示例替换了
PreUpdate.AIUpdate
System,但您可以通过指定 Player Loop 中的 PlayerLoopSystem.类型标识符来替换任何 System。可通过迭代默认 Player Loop (如上一节所示)或从
UnityEngine.PlayerLoop
命名空间获取默认系统的有效类型。
重要
在 Player Loop中替换System可能会产生意外后果,因为它会删除该System的默认功能。请谨慎使用此方法,并且仅在您确定要将默认功能替换为您自己的自定义定义逻辑时。
using UnityEngine.LowLevel;using UnityEngine.PlayerLoop;using UnityEngine;// Replace an existing system in the Unity Player Loop with a custom update.public class MyReplacementCustomUpdate { } // Empty class to use as a type identifier for the custom updatepublic class SystemReplacement{ //Run this method on runtime initialization [RuntimeInitializeOnLoadMethod] private static void AppStart() { // Retrieve the default Player loop system.如果先前已修默认,则获取当前Loop。 var defaultSystems = PlayerLoop.GetDefaultPlayerLoop(); // Create a custom update system to replace an existing one var customUpdate = new PlayerLoopSystem() { updateDelegate = CustomUpdate, type = typeof(MyReplacementCustomUpdate) }; // Specify the system to replace as the type parameter, in this case PreUpdate.AIUpdate ReplaceSystem<PreUpdate.AIUpdate>(引用 defaultSystems、customUpdate); PlayerLoop.SetPlayerLoop(defaultSystems); } // Custom update method that will be called in the Player Loop private static void CustomUpdate() { Debug.Log("Custom update from a replacement system."); } //Recursively replace a system of type T with a replacement system in the Player Loop private Static bool ReplaceSystem<T>(引用 PlayerLoopSystem System、PlayerLoopSystem 替换) { if (system.type == typeof(T)) { system = replacement; return true; } if (system.subSystemList != null) { for (var i = 0; i < system.subSystemList.Length; i++) { if (ReplaceSystem<T>(ref system.subSystemList[i], replacement)) { return true; } } } return false; }}

其他资源和示例