Add singleton API to World

- singleton() combines component() with set()
- get() looks up a singleton component value
- set() sets it, though singleton must exist before
main
copygirl 1 year ago
parent 2a41366bd8
commit 2e36be7ad2
  1. 35
      src/world.zig

@ -95,6 +95,41 @@ pub fn World(comptime ctx: anytype) type {
return Entity(ctx).fromRaw(self, result); return Entity(ctx).fromRaw(self, result);
} }
/// Registers a singleton component of type `T` with the specified value.
///
/// A singleton is a component which has itself added to its entity.
/// This allows looking up a value of `T` using its own type. Only one
/// singleton of each type can exist per world, but other entities may
/// still have this component added to them.
///
/// Use `get()` and `set()` to get and set the value of this singleton.
///
/// Returns the created component entity.
pub fn singleton(self: *Self, comptime T: type, value: T) !Entity(ctx) {
const single = try component(self, T);
single.set(T, value);
return single;
}
/// Gets the value of the singleton component with type `T`.
///
/// Returns `error.IsNotAlive` if the entity is missing.
/// Returns `error.ComponentMissing` if the component is missing.
/// Both of these may occur from not calling `singleton()` first.
pub fn get(self: *Self, comptime T: type) !T {
const e = try self.lookupByType(T);
return e.get(T) orelse error.ComponentMissing;
}
/// Sets the value of the singleton component with type `T`.
///
/// Returns `error.IsNotAlive` if the entity is missing.
/// This may occur from not calling `singleton()` first.
pub fn set(self: *Self, comptime T: type, value: T) !void {
const e = try self.lookupByType(T);
e.set(T, value);
}
pub fn system( pub fn system(
self: *Self, self: *Self,
name: [:0]const u8, name: [:0]const u8,

Loading…
Cancel
Save