Querying the world
You can search the SpatialOS world for entities, using entity queries and a query language.
This is useful if you want to get information about entities, including entities outside the area of the world that your Unreal worker instance knows about. A query can return entity IDs, so you can query for entities that you want to invoke a command on, or delete.
The Unreal integration doesn’t offer wrappers and blueprint integration for entity queries at the moment: it uses the base C++ SDK. This page gives a short introduction to queries, but for a fuller reference, see the C++ worker API section on Entity queries.
Note: In order to send an entity query, a worker must have permission to do so. For more information, see the Worker permissions page.
Example: Building a query
It’s common to have a single “Spawner” entity in the world’s starting snapshot, with a single component Spawner
.
This entity is responsible for creating a player entity for UnrealClient workers when they connect.
To find this entity from the UnrealClient worker, you would build the following query:
const worker::query::EntityQuery& entity_query = {
worker::query::ComponentConstraint { improbable::spawner::Spawner::ComponentId },
worker::query::SnapshotResultType {}
};
Make sure you include the header files of any components you reference.
Sending a query
Send a query and listen for the response by directly using the Connection
and View
exposed by the C++ Worker SDK. The
connection can be accessed from the USpatialOS
object.
To send a query:
auto requestId = spatialOS->GetConnection().SendEntityQueryRequest(entity_query, 0));
Note the example code above assumes that you have access to a pointer to the
USpatialOS
of your project. In the RPG demo example, this object is stored in theURPGDemoGameInstance
.
To listen for a response using the requestId
returned by SendEntityQueryRequest()
:
spatialOS->GetView().OnEntityQueryResponse([this, requestId](const worker::EntityQueryResponseOp& op) {
if (op.RequestId != requestId)
{
return;
}
if (op.StatusCode != worker::StatusCode::kSuccess)
{
std::string errorMessage = "Could not find spawner entity: " + op.Message;
// output error
return;
}
if (op.ResultCount == 0)
{
std::string errorMessage = "Query returned 0 spawner entities";
// output error
return;
}
auto spawnerEntityId = op.Result.begin()->first;
// do something with the spawner's entity ID
});
Note the example code above assumes that you have access to a pointer to the
USpatialOS
of your project. In the RPG demo example, this object is stored in theURPGDemoGameInstance
.