Home > Mobile >  RealityKit – Grab children from USDZ file by name
RealityKit – Grab children from USDZ file by name

Time:08-19

Goal: I have a massive USDZ scene file, with hundreds of layers and objects. Need to grab each object easily, to then manipulate in RealityKit.

Tried: The approach bellow by Andy Jazz is the only solution I found for now:

let entity = scene.children[0].........children[0] as! ModelEntity

Problem: It's impossible to know each USDZ's entity number on the hierarchy.

Is it possible to grab the entity by its name?

import RealityKit

class ViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    
    override func viewDidLoad() {
        super.viewDidLoad()            
        do {
            let path = Bundle.main.path(forResource: "Matrix", ofType: "usdz")!
         
            let url = URL(fileURLWithPath: path)
               
            // Scene
            let scene = try Entity.load(contentsOf: url)          
            print(scene)
            
            // Entity
            let entity = scene.children[0].........children[0] as! ModelEntity
            
            entity.model?.materials[0] = UnlitMaterial(color: .red)
            
            let anchor = AnchorEntity(plane: .any)
            anchor.addChild(scene)
            arView.scene.anchors.append(anchor)

         } catch {
             print(error)
         }
    }
}

CodePudding user response:

Use findEntity(named:) instance method to recursively get any descendant entity by its name.

func findEntity(named name: String) -> Entity?

.rcproject scene

let boxAnchor = try! Experience.loadBox()
arView.scene.anchors.append(boxAnchor)

print(boxAnchor)
    
let entity = boxAnchor.findEntity(named: "Steel Box")
entity?.scale *= 7

.usdz model

let model = try! ModelEntity.load(named: "model.usdz")
let anchor = AnchorEntity(world: [0,0,-1])
anchor.addChild(model)
arView.scene.anchors.append(anchor)
    
print(model)
    
let entity = model.findEntity(named: "teapot")
entity?.scale /= 33

P. S.

Unfortunately, not all entities in .usdz or .rcproject have names by default.

So, you must give all the required names to entities to use this method.

  • Related