Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Last active December 9, 2023 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewolbrich/bf6fde46c4fcae01a856eff58fdc56a1 to your computer and use it in GitHub Desktop.
Save drewolbrich/bf6fde46c4fcae01a856eff58fdc56a1 to your computer and use it in GitHub Desktop.
Entity/enumerateHierarchy
//
// Entity+EnumerateHierarchy.swift
//
// Created by Drew Olbrich on 7/18/23.
//
import RealityKit
extension Entity {
/// Executes a closure for each of the entity's child and descendant entities, as
/// well as for the entity itself.
func enumerateHierarchy(body: (Entity) -> Void) {
enumerateHierarchy { entity, _ in
body(entity)
}
}
/// Asynchronously executes a closure for each of the entity's child and descendant
/// entities, as well as for the entity itself.
///
/// This method does not return until all asynchronous `body` closures have finished
/// executing.
func enumerateHierarchy(body: @escaping (Entity) async -> Void) async {
await withTaskGroup(of: Void.self) { taskGroup in
enumerateHierarchy { entity, _ in
taskGroup.addTask {
await body(entity)
}
}
}
}
/// Executes a closure for each of the entity's child and descendant entities, as
/// well as for the entity itself.
///
/// Set `stop` to true in the closure to abort further processing of the child entity subtree.
func enumerateHierarchy(body: (Entity, UnsafeMutablePointer<Bool>) -> Void) {
var stop = false
func enumerate(body: (Entity, UnsafeMutablePointer<Bool>) -> Void) {
guard !stop else {
return
}
body(self, &stop)
for child in children {
guard !stop else {
break
}
child.enumerateHierarchy(body: body)
}
}
enumerate(body: body)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment