[Entities] Mastering EntityQuery Performance and Creation in Unity 6
Solution
Unity 2022.3.x - Unity 6.3.x
Published 16 days ago
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.
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
EntityQueryBuilderorGetEntityQueryshould be performed exclusively insideOnCreate. - The
SystemAPI.Querymethod used inOnUpdateis a specialized case where the Unity Source Generator creates and caches the EntityQuery at compile-time. - Creating a new
EntityQueryBuilderinsideOnUpdatewill result in significant memory allocations and CPU overhead every frame.
Additional Tips
- For scenarios requiring runtime logic changes, pre-define all possible queries in
OnCreateand store them in aNativeListor array. - Use
RequireForUpdatewith 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.