UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Can SwiftUI environment objects be accessed within SpriteKit Scene?

Forums > SwiftUI

I tried accessing a SwiftUI environment object (that is available to regular SwiftUI views) from within Spritekit, but I am unable to access it. I always get an error indicating that the Environment Object is not available, but I have clearly loaded it before coming to the view containing the Spritekit scene. Can this even be accomplished?

class PlayerScene: SKScene { @EnvironmentObject var usersContainer: UsersContainer //container class with currently logged in users

override func didMove(to view: SKView) {
    for u in usersContainer.users{ //users is an array containing user objects
        let r = u.name //does not work
    }
}
}

2      

I was able to make it work by changing it to an ObservedObject instead of an EnvironmentObject within SpriteKit

2      

I am having the same problem. Can you give me example code that shows how you got it to work?

2      

Yes, more code, please, @sri-dor. I've tried changing @Environment to @ObservedObject but without success. Clearly, I'm missing something. Thanks!

2      

@caldantech...If you are still having the same problem, check out my own reply at https://www.hackingwithswift.com/forums/swiftui/follow-up-to-inquiry-on-spritekit-and-swiftui-integration/6915 Not sure if it is the exact answer you need, but maybe it will help. Good luck!

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.