Help us understand the problem. What is going on with this article?

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

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
}

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away