1

Components of entities can be removed with:

entity.removeComponentForClass(SpriteComponent.self);
entity.removeComponentForClass(PhysicsComponent.self);

How are Entities removed from a SKScene?

There are plenty of tutorials about removing components, but I can't find anything explicit about removing entities. Is there something like removing a node?

node.removeFromParent();
Anders Evensen
  • 579
  • 5
  • 15
dancingbush
  • 2,131
  • 5
  • 30
  • 66
  • This entirely depends on how you store and reference the `entity` instance. If you wish to stop updating an entity, just don't call its `update` method. The `.removeFromParent` method allows you to remove a node from SpriteKit's node tree, which Sprite Kit manages. Managing GKEntities is upto your custom code - e.g. entities can be stored in an array and removed from them – Benzi Jan 28 '17 at 17:05
  • Thanks, tej entities are managed in a Set and added to the scene, I can remove the entity From the Set after it has been Added to the scene, but can't remove from the scene directly, although I can remove all its components – dancingbush Jan 28 '17 at 17:20
  • I have almost two weeks trying to solve the same problem. Did you ever find a solution? – iOSTony Apr 06 '17 at 16:28
  • Nope never, project on hold at tej minute but never got it, kept crashing as a reference was been held somewhere for the entity when it should of been removed – dancingbush Apr 06 '17 at 16:37

1 Answers1

0

I adapted this from Apple's DemoBots which contains samples for the RenderComponent and LayerConfiguration.

Array was extended using Swift solution here >> Array extension to remove object by value

var entities = [GKEntity]()

/// Stores a reference to the root nodes for each world layer in the scene.
var layerNodes = [LayerConfiguration:SKNode]()

func addEntity(entity: GKEntity)
{
    self.entities.append(entity)

    for componentSystem in self.componentSystems
    {
        componentSystem.addComponent(foundIn: entity)
    }

    // If the entity has a `RenderComponent`, add its node to the scene.
    if let renderNode = entity.component(ofType: RenderComponent.self)?.node
    {
        self.addNode(node: renderNode, toLayer: .actors)
    }
}

func removeEntity(entity:GKEntity)
{
    for componentSystem in self.componentSystems
    {
        componentSystem.removeComponent(foundIn: entity)
    }

    if let renderNode = entity.component(ofType: RenderComponent.self)?.node
    {
       renderNode.removeFromParent()
    }

    self.entities.remove(entity)
}

func addNode(node: SKNode, toLayer layer: LayerConfiguration)
{
    // 
    let layerNode = self.layerNodes[layer]!

    layerNode.addChild(node)
}
Tim Newton
  • 1,463
  • 1
  • 13
  • 13