Query for changed entities
Updated: Jun 20, 2025
The changedSince query is an advanced, experimental API. It retrieves entities that changed since a specified DataModel version. The DataModel version increments each time the DataModel changes.
The changedSince query takes two parameters:
- The component ID to track changes for
- A
DataModel version number
When the query runs, it returns only entities whose specified component has been modified since the provided version number.
Here’s an example from the GrabbablePhysicsSystem that demonstrates how to use the changedSince query:
class GrabbablePhysicsSystem() : SystemBase() {
private var lastUpdateVersion = 0UL
@OptIn(SpatialSDKExperimentalAPI::class)
override fun execute() {
val q = Query.where { changedSince(Grabbable.id, lastUpdateVersion) and has(Physics.id) }
lastUpdateVersion = EntityContext.getDataModel()!!.getLastUpdateVersion()
for (entity in q.eval()) {
...
}
}
override fun getDependencies(): SystemDependencies? {
return SystemDependencies(
mustRunBefore =
mutableSetOf(SystemDependencyConfig(GrabbableSystem::class, isRequired = false)),
mustRunAfter = mutableSetOf(SystemDependencyConfig(TickPhysicsSystem::class)))
}
}
In this example:
- The system creates a query that finds all entities where:
- The
Grabbable component has changed since lastUpdateVersion - The entity also has a
Physics component
- After executing the query, the system updates
lastUpdateVersion to the current DataModel version - The system then processes the query results.
This approach removes the one tick lag of the changed API, which makes sure that the GrabbablePhysicsSystem can process the entities that have been set a Grabbable component in the same tick.
To use changedSince queries effectively, you need to:
- Maintain a version number variable (like
lastUpdateVersion in the example) - Update this version number after processing the query results
- Use this updated version number in the next query execution
The current version of the data model can be obtained using the getLastUpdateVersion method of the DataModel class:
@SpatialSDKExperimentalAPI
fun getLastUpdateVersion(): ULong {
//
}