使用自定义更新管理员器
创建更新管理员以手柄每帧许多更新。
阅读时间5 分钟最后更新于 5 天前
Unity 内置的每帧事件函数更新(例如、和)可能会缩放性能。尽管 C# MonoBehaviour 脚本会调用相应的回调,但函数 Calls 源自 Unity 的原生代码。Unity 必须维护内部列表来轨道要调用 ON 更新函数的对象。MonoBehaviour 脚本实例分别在已启用或DisabledWhen添加到这些列表中或从中已移除。
UpdateFixedUpdateLateUpdate虽然向 Project 中需要它们的每个 MonoBehaviour 实例添加适当的回调很方便,但随着回调数量的增加,这会变得更加低效。从原生代码调用 Managed 代码回调会产生很小但很大的开销,从而导致以下后果:
- 调用大量回调时的降级帧时间。
Update - 当实例化预制件包含大量 MonoBehaviour 时,由于调用预制件中每个组件的 和
Awake回调会产生性能开销,导致实例化时间降低。OnEnable
为了避免这些问题,可以创建全局自定义更新管理员单例实例,并让 MonoBehaviour 脚本甚至标准 C# 对象订阅该实例,而不必依赖 ON 内置回调。这样,更新管理员单例可将、和其他回调分发给已订阅它们的所有对象,并且所有更新代码都保留在 Managed 图层中。这样做的另一个优点是允许在没有要执行的操作When取消订阅回调的代码,从而减少帧必须调用的函数数量。
UpdateLateUpdateWhen使用自定义定义更新管理员器
当具有每帧更新回调的 MonoBehaviour 实例数量达到数百或数千时,自定义更新管理员可能很有用。
通过消除很少执行的回调,可以显著提高性能。请参考以下示例:
void Update() { if(!someVeryRareCondition) { return; }// … some operation …}
如果 Project 有许多具有类似回调的 MonoBehaviour,则 running 回调所消耗的大量时间将用于在原生和 Managed 代码域之间切换以便执行 MonoBehaviour,然后立即退出。如果这些类仅在 为 true 时订阅全局更新管理员,并在此后取消订阅,则 ON 切换代码域和评估罕见条件所用的时间都会减少。
UpdateUpdatesomeVeryRareCondition自定义定义更新管理员器示例
要实现自定义定义更新管理员器,请首先创建一个 C# Script定义接口,如下所示:
public interface IUpdatable{ void CustomUpdate(float deltaTime);}
然后,可以为更新管理员单例创建 MonoBehaviour 脚本。更新管理员实现了内置回调,然后 Other MonoBehaviour 脚本组件可以订阅此更新管理员而不是直接订阅:
UpdateUpdate// Singleton update manager. Attach to a GameObject in your scene.using System.Collections.Generic;using UnityEngine;public class UpdateManager :MonoBehaviour{ private static UpdateManager _实例; public static UpdateManager Instance => _instance; private 只读列表<IUpdatable>可更新项 = 新建列表<IUpdatable>(); void Awake() { if (_instance == null) _instance = this; else Destroy(gameObject); } public void Register(IUpdatable updatable) { if (!updatables.Contains(updatable)) updatables.Add(updatable); } public void Unregister(IUpdatable updatable) { updatables.Remove(updatable); } void Update() { 浮点 DeltaTime = 时间。deltaTime; // Optionally: for performance, iterate backwards if you allow removal during iteration Foreach(可更新项中的可更新项) { updatable.CustomUpdate(deltaTime); } }}
最后,创建 MonoBehaviour 脚本组件,该组件在 On Enable 时向更新管理员实例注册,而在 On Disable 时取消注册。以下示例使用自定义定义更更新回调来Move父游戏对象对象:
// Script component. Attach to a GameObject in your scene to move it on each custom update.using UnityEngine;public class MyMovingObject :MonoBehaviour、可更新{ void OnEnable() { UpdateManager.Instance.Register(this); } void OnDisable() { if (UpdateManager.Instance != null) UpdateManager.Instance.Unregister(this); } public void CustomUpdate(float deltaTime) { // Your update logic here 变换。位置 += Vector3.right * DeltaTime; }}
其他资源
- ��� 文档: 事件函数执行 Order
- ��� 文档:事件函数
- ��� 文档: 10000 Update Calls