Binding to a value of a Component of Entity?

I have a HealthComponent and a HealthSystem which decreases the health value for all Entities with the HealthComponent every 2 seconds in the update loop of the system.

Now if, in a SwiftUI view, I want to show the current health value and bind to it, how would I do this?

Ive tried adding the entity to my Character struct bit that obviously doesn’t update by itself.

Found out how to do it, but not sure if this is the correct way. This is my component now:


class HungerComponent: Component {
    
    var hungerValue: Int = 100
    var passedTime: TimeInterval = TimeInterval(0)
    let updateInterval: TimeInterval = TimeInterval(2)
    var hungerPublisher = PassthroughSubject<Int, Never>()

    required init(hungerValue: Int = 100) {
        self.hungerValue = hungerValue
    }
    
    func decreaseHunger() {
            hungerValue -= 1
            hungerPublisher.send(hungerValue)
        }
}

And I just add a sink to it in my view:

    init(cube: Cube) {
        self.cube = cube
        if let entity = cube.entity, let hungerComponent = entity.components[HungerComponent.self] {
            hungerComponent.hungerPublisher
                .sink(receiveValue: { [weak self] hungerValue in
                    self?.hungerPercentage = Float(hungerValue) / 100.0
                })
                .store(in: &cancellables)
        }
    }

If you found out any other way please do tell how.

Actually, using the new @Observable seems to be a better choice for this, I used it like this:

import Foundation
import RealityKit
import Combine
import Observation

@Observable
class HungerComponent: Component {
    
    var hungerValue: Int = 100
    var passedTime: TimeInterval = TimeInterval(0)
    let updateInterval: TimeInterval = TimeInterval(2)

    required init(hungerValue: Int = 100) {
        self.hungerValue = hungerValue
    }
}

And then I simply access it within my ViewModel like this:

    init(character: Character) {
        character = character
        self.hungerComponent = character.entity?.components[HungerComponent.self] ?? HungerComponent()
    }

Which makes it accessible within the View like this:

Text("Hunger: \(viewModel.hungerComponent.hungerValue)")
Binding to a value of a Component of Entity?
 
 
Q