I’m implementing my first Component Entity System and am having an issue. I have a requirement that some component properties be dynamic. I do not want to create a subclass that conforms to HasExampleComponent, so this was my approach. My issue is that even though the entity contains the property I can’t cast it to HasExampleComponent.
When I create the entity I set the component like this:
entity.components[ExampleComponent.self] = .init()
I'd appreciate a template for a ECS with component properties that can be updated from the app. Thanks
public struct ExampleComponent: Component {
public var value = 0
}
public protocol HasExampleComponent: Entity {
var value: Int
}
public class ExampleSystem: System {
private static let query = EntityQuery(where: .has(ExampleComponent.self))
public required init(scene: Scene) {}
public func update(context: SceneUpdateContext) {
context.scene.performQuery(Self.query).forEach { entity in
// this won’t work because entity doesn’t conform to HasExampleComponent
entity.value += 1
}
}
}
extension Entity {
@available (iOS 15.0, *)
public var value: Int? {
get { components[RotatingComponent.self].value ?? 0}
set { components[RotatingComponent.self].value = newValue }
}
}