Skip to content

Game.SafeCommandBufferSystem

Assembly:
Namespace: Game

Type: class

Base: Unity.Entities.EntityCommandBufferSystem

Summary: A small wrapper around EntityCommandBufferSystem that enforces a simple usage window for creating EntityCommandBuffer instances. The system exposes AllowUsage() to enable creation of command buffers, and prevents creation once the system's OnUpdate has begun by throwing an Exception. Intended to help catch incorrect command-buffer creation outside intended times (for example, after updates started).


Fields

  • private bool m_IsAllowed Tracks whether creating an EntityCommandBuffer is currently allowed. Initialized to true. Set to false at the start of OnUpdate to prevent creating new buffers while the system is updating.

Properties

  • (none)

Constructors

  • public SafeCommandBufferSystem() Default constructor. Marked with [Preserve] in the source to avoid stripping by Unity's managed code stripping.

Methods

  • public void AllowUsage() Enables creation of EntityCommandBuffer instances by setting m_IsAllowed to true. Call this before calling CreateCommandBuffer when you want to allow buffer creation for a specific scope.

  • public new EntityCommandBuffer CreateCommandBuffer() Hides EntityCommandBufferSystem.CreateCommandBuffer(). Returns an EntityCommandBuffer if m_IsAllowed is true; otherwise throws an Exception with message "Trying to create EntityCommandBuffer when it's not allowed!". Use the system's AllowUsage() to enable creation beforehand. Note: this method uses the C# new keyword (method hiding), not override.

  • protected override void OnUpdate() : System.Void Marked with [Preserve]. When the system updates, this sets m_IsAllowed to false and then calls base.OnUpdate(). This effectively disallows creating new command buffers once an update starts.

Usage Example

// Example usage from another system or initialization code:

public class SomeSystem : SystemBase
{
    private SafeCommandBufferSystem _safeEcbSystem;

    protected override void OnCreate()
    {
        base.OnCreate();
        _safeEcbSystem = World.GetOrCreateSystem<SafeCommandBufferSystem>();
    }

    protected override void OnUpdate()
    {
        // Allow creation for this frame (or specific scope) before creating buffers
        _safeEcbSystem.AllowUsage();

        // Safe to call CreateCommandBuffer() now
        var ecb = _safeEcbSystem.CreateCommandBuffer();
        // ... record entity commands ...

        // Note: Once SafeCommandBufferSystem.OnUpdate runs, CreateCommandBuffer() will throw
        // if called without calling AllowUsage() first.
    }
}

Additional notes: - The primary purpose is to make incorrect command-buffer creation obvious (via exception) rather than silently allowing misuse. - Because CreateCommandBuffer is hidden (new), ensure you call it on a SafeCommandBufferSystem reference rather than on an EntityCommandBufferSystem reference if you need the safety check.