Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@noppefoxwolf

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
0
Help us understand the problem. What are the problem?