Canvatorium Visio Lab 5034
Edit property values on existing PhysicallyBasedMaterials
This lab imports a scene from Reality Composer Pro and provides some buttons to update the diffuseColor of a PhysicallyBasedMaterial.
Special thanks to Andy J. for pointing out that I should have casted the material to PhysicallyBasedMaterial.
From what I can tell, we always have to copy the existing component, modify it, then set it back to the target entity. Hopefully visionOS 2.0 will make this a bit easier.
struct Lab5034: View {
@State var color: UIColor = .systemRed
var body: some View {
ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)) {
RealityView { content in
if let root = try? await Entity(named: "GestureLab", in: realityKitContentBundle) {
root.position = [0, -0.45, 0]
root.scale = [2,2,2]
content.add(root)
let cube = root.findEntity(named: "Cube") as! ModelEntity
// Get the material as a as! PhysicallyBasedMaterial
var mat = cube.model?.materials.first as! PhysicallyBasedMaterial
mat.baseColor.tint = color
cube.model?.materials[0] = mat
}
} update: { content in
if let root = content.entities.first {
let cube = root.findEntity(named: "Cube") as! ModelEntity
var mat = cube.model?.materials.first as! PhysicallyBasedMaterial
mat.baseColor.tint = color
cube.model?.materials[0] = mat
}
}
.toolbar {
ToolbarItemGroup(placement: .bottomOrnament) {
Button {
color = .systemRed
} label: {
Text("R")
}
.foregroundColor(color == .systemRed ? .red : .white)
Button {
color = .systemGreen
} label: {
Text("G")
}
.foregroundColor(color == .systemGreen ? .green : .white)
Button {
color = .systemBlue
} label: {
Text("B")
}
.foregroundColor(color == .systemBlue ? .blue : .white)
}
}
}
}
}