I’m new to SwiftUI and RealityKit and I was wondering how I can change the color of an entity with a transition. Here’s some code I wrote to change the color of a cube when it is tapped:
import SwiftUI
import RealityKit
import RealityKitContent
struct ContentView: View {
@State var color = SimpleMaterial.Color(.red)
private let colors: [SimpleMaterial.Color] = [.red, .green, .blue, .orange, .yellow]
static var cubeEntity = Entity()
var body: some View {
VStack {
RealityView { content in
// Add the initial RealityKit content
if let cube = try? await Entity(named: "MyCube", in: realityKitContentBundle) {
content.add(cube)
ContentView.cubeEntity = cube
}
} update: { content in
let selectedMaterial = SimpleMaterial(color: color, isMetallic: false)
let modelEntity = ContentView.cubeEntity.findEntity(named: "MyCube") as! ModelEntity
// how can I add a transition to this?
modelEntity.model?.materials[0] = selectedMaterial
}
.gesture(SpatialTapGesture().targetedToAnyEntity().onEnded { _ in
color = colors.randomElement()!
})
}
}
}
#Preview(windowStyle: .volumetric) {
ContentView()
}
I’m also not sure if the way I’m targeting the cube to change the color is aligned with best practices so would love some feedback on that if there’s a better way!