Skip to content
Flecs v4.1
entities/get_n

  • C++

    View on GitHub

    1#include <get_n.h>
    2#include <iostream>
    3
    4/* This code shows how to get multiple components in a single command */
    5
    6struct Position {
    7 double x, y;
    8};
    9
    10struct Mass {
    11 double value;
    12};
    13
    14struct Velocity {
    15 double x, y;
    16};
    17
    18int main(int, char *[]) {
    19 flecs::world ecs;
    20
    21 // Create new entity, set Position and Mass component
    22 flecs::entity e = ecs.entity()
    23 .insert([](Position& p, Mass& m) {
    24 p.x = 10;
    25 p.y = 20;
    26 m.value = 100;
    27 });
    28
    29 {
    30 auto [pos, mass] = e.get_mut_n<Position, Mass>();
    31 pos.x += 5;
    32 mass.value += 3;
    33 std::cout << "Position: {" << pos.x << ", " << pos.y << "}\n";
    34 std::cout << "Mass: {" << mass.value << "}\n";
    35 // Output:
    36 // Position: {15, 20}
    37 // Mass: {103}
    38 }
    39 std::cout << "\n";
    40 {
    41 const auto [pos, mass] = e.get_n<Position, Mass>();
    42 // pos.x += 5; // Will not compile here!
    43 // mass.value += 3; // Will not compile here!
    44 std::cout << "Position: {" << pos.x << ", " << pos.y << "}\n";
    45 std::cout << "Mass: {" << mass.value << "}\n";
    46 // Output:
    47 // Position: {15, 20}
    48 // Mass: {100}
    49 }
    50 std::cout << "\n";
    51 // It's possible to try_get_n with absent component that will return null
    52 {
    53 const auto [pos, velocity, mass] = e.try_get_n<Position, Velocity, Mass>();
    54
    55 std::cout << "Position: {" << pos->x << ", " << pos->y << "}\n";
    56 if (velocity) {
    57 std::cout << "Velocity: {" << velocity->x << ", " << velocity->y << "}\n";
    58 } else {
    59 std::cout << "Velocity: not found\n";
    60 }
    61 std::cout << "Mass: {" << mass->value << "}\n";
    62 // Output:
    63 // Position: {15, 20}
    64 // Velocity: not found
    65 // Mass: {100}
    66 }
    67
    68 return 0;
    69}
    flecs::entity entity(Args &&... args) const
    Create an entity.
    Definition impl.hpp:195
    const Self & insert(const Func &func) const
    Set 1..N components.
    Definition impl.hpp:23
    Entity.
    Definition entity.hpp:30
    The world.
    Definition world.hpp:129