RealityKit – How to access the property in a Scene programmatically?
Of course, you need to look for the required ModelEntity in the depths of the model's hierarchy.
Use this SwiftUI solution:
struct ARViewContainer: UIViewRepresentable {
func makeUIView(context: Context) -> ARView {
let arView = ARView(frame: .zero)
let pictureScene = try! Experience.loadPicture()
pictureScene.children[0].scale *= 4
print(pictureScene)
let edgingModel = pictureScene.masterpiece?.children[0] as! ModelEntity
edgingModel.model?.materials = [SimpleMaterial(color: .brown,
isMetallic: true)]
var mat = SimpleMaterial()
// Here's a great old approach for assigning a texture in iOS 14.5
mat.baseColor = try! .texture(.load(named: "MonaLisa", in: nil))
let imageModel = pictureScene.masterpiece?.children[0]
.children[0] as! ModelEntity
imageModel.model?.materials = [mat]
arView.scene.anchors.append(pictureScene)
return arView
}
func updateUIView(_ uiView: ARView, context: Context) { }
}
Is there a way to programmatically change the material of an Entity that was created in Reality Composer?
Model entity is stored deeper in RealityKit's hierarchy, and as you said, it's Entity
, not ModelEntity
. So use downcasting to access mesh
and materials
:
import UIKit
import RealityKit
class ViewController: UIViewController {
@IBOutlet var arView: ARView!
override func viewDidLoad() {
super.viewDidLoad()
let boxScene = try! Experience.loadBox()
print(boxScene)
let modelEntity = boxScene.steelBox?.children[0] as! ModelEntity
let material = SimpleMaterial(color: .green, isMetallic: false)
modelEntity.model?.materials = [material]
let anchor = AnchorEntity()
anchor.scale = [5,5,5]
modelEntity.setParent(anchor)
arView.scene.anchors.append(anchor)
}
}
Related Topics
Value for Swift_Version Cannot Be Empty
How to Install Package in Xcode via Swift Package Manager
Swift Uisearchcontroller Wired Up in Core Data Project, App Runs, But Search Not Updating
How to Set Title of Navigation Bar in Swift
Swiftui - How to Use Oncommand with Nsmenuitem on MACos
Convert or Cast Object to String
Calculating Angle Between Two Points on Edge of Circle Swift Spritekit
Sliding One Swiftui View Out from Underneath Another
How Are the Arkit People Occlusion Samples Being Done
Arkit - How to Put 3D Object on Qrcode
Convert Swift Dictionary to String
Mutate Function Parameters in Swift
Swiftui: Detect Finger Position on MAC Trackpad
Swift Delegate for a Generic Class
Sprite-Kit: Moving an Element in Circular Path