Search code examples
swiftreferencescenekitios10particle-system

Get reference to a Particle System created in Scene Editor


I've created a particle system in the Scene Editor (not the particle Editor), and it's named "particles" (this is the default name).

Back in the ViewController, I'm attempting to get a reference to this particle system and change some properties of it.

But I can't figure out why this doesn't work:

let particleSystem = SCNParticleSystem(named: "particles", inDirectory: "")
        particleSystem?.isAffectedByGravity = true

I know it's possible to set gravity on within the Scene Editor, but I'm simply using this as a test to see if the reference to the Particle System is working. It's not.

What am I missing or doing wrong?

ADDITIONAL EFFORTS:

As per Rickster's suggestion, trying this:

 let particleSystems = scene.particleSystems
    let myParticleSystem = particleSystems?[0]
    myParticleSystem?.isAffectedByGravity = true
    print(particleSystems)

This has now this problem:

enter image description here

My thinking (faulty as it is) was that the array's 0 location would have the only particle system I have in this scene.


Solution

  • Here is a picture of the scene I got:

    SCNParticleSystem instance assigned to SCNNOde

    And the code to get a reference to the particle system assigned to the particles SCNNode instance:

    In Swift 2.3 (and earlier)

     let particlesNode:SCNNode = scene.rootNode.childNodeWithName("particles", recursively: true)!
     let particleSystem:SCNParticleSystem = (particlesNode.particleSystems?.first)!
    

    In Swift 3.0

     let particlesNode:SCNNode = scene.rootNode.childNode(withName: "particles", recursively: true)!
     let particleSystem:SCNParticleSystem = (particlesNode.particleSystems?.first)!
    

    Alternative Array Index Syntax

     let particleSystem:SCNParticleSystem = (particlesNode.particleSystems?[0])!