Is there a way to programmatically tint(darken) the material of an Entity that was created in Reality Composer?

67 views Asked by At

From the linked pages below, I've been able to change the color to a solid green. However, I just want to darken the existing material of multiple 3d models each of which have different color schemes.

Their color schemes are based off of a png I've given each model as a physically based material, not sure if this really affects anything big picture. I really do not want have to go into reality composer and make a custom darker color palette for every model...

I would also like the material change respond to input data, not a hard-coded change. I've made a model entity and have been able to change the color manually.

content.add(michelleSceneEntity)

guard let michelleJumpModel = michelleSceneEntity.findEntity(named: "michelle_jump") else { return }
            
let modelEntity = michelleJumpModel.children[0].children[0] as! ModelEntity
            
print(modelEntity)
            
guard let michelleJumpAnimationResource = michelleJumpModel.availableAnimations.first else { return }
let michelleJumpAnimation = try AnimationResource.sequence(with: [michelleJumpAnimationResource.repeat()])
            
let material = SimpleMaterial(color: .green, isMetallic: false)     
modelEntity.model?.materials = [material]
                       
// michelleSceneEntity.model?.materials = [material]           
michelleJumpModel.playAnimation(michelleJumpAnimation.repeat())
1

There are 1 answers

0
Andy Jazz On

Yes, you definitely can programmatically tint a material in RealityKit visionOS app. For that you need a texture file (if you have a USDA file it's not a problem I suppose, however, if you have a USDZ file, read this post to find out how to extract textures from a zero archive).

enter image description here

Here's the code:

import SwiftUI
import RealityKit

struct ContentView : View {
    var material = SimpleMaterial()

    init() {
        material.color.texture = try? .init(.load(named: "diffuse"))
        material.color.tint = .lightGray
    }
    var body: some View {
        RealityView { content in
            if let character1 = try? await Entity(named: "Character") {
                character1.position = [-1.2, 0.0,-3.0]
                content.add(character1)
            }
            if let character2 = try? await Entity(named: "Character") {
                character2.position = [1.2, 0.0,-3.0]
                content.add(character2)
                
                print(character2)   // ModelEntity is "Object_0"
                
                let entity = character2.findEntity(named: "Object_0") as! ModelEntity
                entity.model?.materials = [material]
            }
        }
    }
}

enter image description here