Search code examples
swiftsprite-kitgameplay-kit

Why can't I add my component to a GKComponentSystem?


My code:

bunnyE = MyEntity()
var wsc : WrappableSpriteComponent = WrappableSpriteComponent()
wsc.setSprite(sprite: bunny!)
bunnyE?.addComponent(wsc)
wrappableComponentSystem = GKComponentSystem<WrappableSpriteComponent>()
wrappableComponentSystem!.addComponent(foundIn: bunnyE!)

self.lastUpdateTime = 0 //Break point here

When I step through my code to the break point, I find that in Xcode if I execute the command:

po bunnyE?.components 

Then I can see that bunnyE has the component I added.

But if I do:

 po self.wrappableComponentSystem?.components

Then it seems that the wrappableComponentSystem has no components.

I checked in my scenes update function and found the same result:

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    // Initialize _lastUpdateTime if it has not already been
    if (self.lastUpdateTime == 0) {
        self.lastUpdateTime = currentTime
    }

    // Calculate time since last update
    let dt = currentTime - self.lastUpdateTime

    // Update entities
    for entity in self.entities {
        entity.update(deltaTime: dt)
    }

    self.lastUpdateTime = currentTime
    self.wrappableComponentSystem?.update(deltaTime: currentTime) // Breakpoint
}

At this breakpoint as well, I can see that my bunnyE entity has the component, but my wrappableComponentSystem does not. I have verified that my wrappableComponentSystem is not nil.

I am using swift5, Xcode 11.4, iOS 13.4

What is the mistake I am making ?


Solution

  • I have discovered a problem in this line:

    wrappableComponentSystem = GKComponentSystem<WrappableSpriteComponent>()
    

    If I change it to:

    wrappableComponentSystem = GKComponentSystem(componentClass: WrappableSpriteComponent.self)
    

    Then in the same block when I add a component, and do po wrappableComponentSystem, I can see a single element has been added.

    The problem is, by the time the update method of my scene is triggered, it appears that my wrappableComponentSystem doesn't contain any components anymore.

    Then I changed the declaration line in my class from:

    private var wrappableComponentSystem : GKComponentSystem<WrappableSpriteComponent>?
    

    where WrappableSpriteComponent inherits from GKComponent, to:

    private var wrappableComponentSystem : GKComponentSystem<GKComponent>?
    

    Now when I add a component, it persists.