Add subscripts to access components of entity
This commit is contained in:
parent
13d0ea9f80
commit
f72723c123
|
|
@ -31,4 +31,23 @@ extension Entity {
|
|||
let compC: C? = get(component: C.self)
|
||||
return (compA, compB, compC)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript<C: Component, Value>(_ componentKeyPath: WritableKeyPath<C, Value>) -> Value? {
|
||||
nonmutating set {
|
||||
guard var comp = self.get(component: C.self),
|
||||
let value = newValue else {
|
||||
return
|
||||
}
|
||||
comp[keyPath: componentKeyPath] = value
|
||||
}
|
||||
get {
|
||||
self.get(component: C.self)?[keyPath: componentKeyPath]
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript<C: Component>(_ componentType: C.Type) -> C? {
|
||||
self.get(component: componentType)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -81,6 +81,33 @@ class EntityTests: XCTestCase {
|
|||
|
||||
XCTAssertEqual(generator.count, 1)
|
||||
}
|
||||
|
||||
func testEntitySubscripts() {
|
||||
let nexus = Nexus()
|
||||
let pos = Position(x: 12, y: 45)
|
||||
let name = Name(name: "SomeName")
|
||||
let entity = nexus.createEntity(with: pos, name)
|
||||
|
||||
XCTAssertEqual(entity[\Position.x], 12)
|
||||
XCTAssertEqual(entity[\Position.y], 45)
|
||||
XCTAssertEqual(entity[\Name.name], "SomeName")
|
||||
|
||||
entity[\Position.x] = 67
|
||||
entity[\Position.y] = 89
|
||||
entity[\Name.name] = "AnotherName"
|
||||
|
||||
XCTAssertEqual(entity[\Position.x], 67)
|
||||
XCTAssertEqual(entity[\Position.y], 89)
|
||||
XCTAssertEqual(entity[\Name.name], "AnotherName")
|
||||
|
||||
entity[\Velocity.a] = 123
|
||||
XCTAssertNil(entity[\Velocity.a])
|
||||
|
||||
entity[Position.self]?.x = 1234
|
||||
XCTAssertEqual(entity[Position.self]?.x, 1234)
|
||||
XCTAssertNil(entity[Velocity.self]?.a)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ extension EntityTests {
|
|||
("testEntityEquality", testEntityEquality),
|
||||
("testEntityIdentifierAndIndex", testEntityIdentifierAndIndex),
|
||||
("testEntityIdGenerator", testEntityIdGenerator),
|
||||
("testEntitySubscripts", testEntitySubscripts),
|
||||
("testRemoveAllComponentsFromEntity", testRemoveAllComponentsFromEntity)
|
||||
]
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue