Act on @state changes only when that state has changed

I have a RealityKitView, and I want to update my scene when some @State value has changed, but I only want to take this action on the frame that the change happens. assuming I have something like

@State private var someState = false

in my update I want to take actions like this.

RealityView { content in
    // Add the initial RealityKit content
} update: { content in
   
    //I want to do something only when someState has changed.
    if(someState != lastValueForSomeState){
        //do something to my content that Is expensive and
        //shouldn't happen every time state changes
     }
     lastValueForSomeState = someState
}  

I am aware that I can use the .onChange(of:) modifier to do normal ui operations, but I don't know where or if I can declare it in a place where I have access to the RealityKitContent.

I can also imagine ways I could do this with components and systems, but it seems like I should be able to do this without going there. is there some mechanism I'm missing for this?

I guess there is nothing that prevents me from doing things like saving Entities to a global var or something similar, then acting on them in the .onChange(of:) code.

Hello,

I guess there is nothing that prevents me from doing things like saving Entities to a global var or something similar, then acting on them in the .onChange(of:) code.

Right, the typical thing to do here is to have a reference to your root Entity accessible at the point you need it, something like this:

    
    @State private var someState = false
    
    var body: some View {
        RealityView { content in
            content.add(root)
        }
        .onChange(of: someState) { _, _ in
            // Do something in your scene here.
            print(root)
        }
    }

Yeah. the way it hands me the RealityContent only in certain closures lead me to believe that somehow it was a transient object that I couldn't rely on being the same from frame to frame. After digging through some samples like Happy Beam, I realize that, no, they are just convenient places where I can grab stuff important to me. It seems the only thing I need to worry about is that I am responsible for releasing my hold on any Entities I might grab.

thanks for the confirmation

Act on @state changes only when that state has changed
 
 
Q