UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

architecture

[Entities] Mastering EntityQuery Performance and Creation in Unity 6

Solution

dotsperformanceproject architectureECSoptimization

Unity 2022.3.x - Unity 6.3.x

Published 16 days ago

Issue

 Developers often experience significant performance spikes and memory allocations when improperly utilizing EntityQueryBuilder or SystemAPI inside the OnUpdate loop of your system. Clarification is required on whether manual creation via GetEntityQuery or automated SystemAPI.Query calls is optimal for runtime conditions.

Explanation

In the Unity Data-Oriented Technology Stack (DOTS), an EntityQuery acts as a dynamic filter. While components are registered at startup, the archetypes they form can appear at any time. The internal system automatically updates existing EntityQuery instances to include these new archetypes without manual intervention.

  • EntityQuery construction is an expensive operation involving hashing and registration within the EntityManager.
  • Manual creation via EntityQueryBuilder or GetEntityQuery should be performed exclusively inside OnCreate.
  • The SystemAPI.Query method used in OnUpdate is a specialized case where the Unity Source Generator creates and caches the EntityQuery at compile-time.
  • Creating a new EntityQueryBuilder inside OnUpdate will result in significant memory allocations and CPU overhead every frame.

Additional Tips

  • For scenarios requiring runtime logic changes, pre-define all possible queries in OnCreate and store them in a NativeList or array.
  • Use RequireForUpdate with your cached EntityQuery to prevent systems from running when specific data is missing.
  • If utilizing ISystem, ensure you store the EntityQuery handle in the system state or as a member variable.

TL;DR

To ensure high frame rates and avoid GC allocations, an EntityQuery must be initialized in OnCreate, while SystemAPI.Query remains the standard for performant iteration within OnUpdate.


Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.