LoginSignup
0
0

More than 3 years have passed since last update.

UnityのTransformのように、SCNNodeのchildrenをfor-inで回せるようにする

Posted at

UnityのTransformはIteratorによって自身のchild-Transformをfor-inで回すことができます

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Example() {
        foreach (Transform child in transform) {
            child.position += Vector3.up * 10.0F;
        }
    }
}

https://docs.unity3d.com/ja/2017.4/ScriptReference/Transform.html より

SceneKitのSCNNodeはchildNodesを持っているためchildNodeを取り出すときは次のようにfor-inします


for childNode in node.childNodes {
  // do anythings
}

UnityC#のようにfor-inしたい場合はカスタムイテレータを定義することで実現できます。


extension SCNNode: Sequence {
    public func makeIterator() -> some IteratorProtocol {
        SCNNode.ChildNodeIterator(self)
    }
}

extension SCNNode {
    struct ChildNodeIterator: IteratorProtocol {
        private let node: SCNNode
        private var index: Int = 0

        init(_ node: SCNNode) {
            self.node = node
        }

        mutating public func next() -> SCNNode? {
            defer { index += 1 }
            guard index < node.childNodes.count else { return nil }
            return node.childNodes[index]
        }
    }
}

これで

for childNode in node {
  // do anythings
}

と実行できるようになりました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0