Last active
December 9, 2023 02:37
-
-
Save drewolbrich/bf6fde46c4fcae01a856eff58fdc56a1 to your computer and use it in GitHub Desktop.
Entity/enumerateHierarchy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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