Getting an Updated Value Through @EnvironmentObject

I have a simple project as follows.

import SwiftUI

class GameSettings: ObservableObject {
	@Published var score: Int = 100
}

struct ContentView: View {
	@StateObject var settings = GameSettings()
	
	var body: some View {
		GeometryReader { geo in
			ZStack {
				HStack(spacing: 0.0) {
					RightView().environmentObject(GameSettings())
						.frame(width: geo.size.width / 2.0, height: geo.size.height)
					Spacer()
				}
				VStack {
					HStack {
						Spacer()
						Button {
							print("\(settings.score)")
						} label: {
							Text("Print")
								.font(.largeTitle)
						}.padding(.trailing, 40.0)
					}
					Spacer()
				}
			}
		}
	}
}

struct RightView: View {
	@EnvironmentObject var settings: GameSettings
	
	var body: some View {
		ZStack {
			Color.red
			Button {
				settings.score += 100
			} label: {
				Text("Change")
					.font(.largeTitle)
			}
		}.environmentObject(settings)
	}
}

So the score is supposed to increase by 100 if I tap the button over the red area. And I want to print the latest value by tapping the Print button at the top-right corner. But it will remain at 100. What am I doing wrong? And can I achieve my goal without using an @ObservedObject variable? Thanks.

Answered by Claude31 in 708780022

Why do you pass an empty GameTttings

				RightView().environmentObject(GameSettings())

and not

				RightView().environmentObject(settings)
Accepted Answer

Why do you pass an empty GameTttings

				RightView().environmentObject(GameSettings())

and not

				RightView().environmentObject(settings)
import SwiftUI

struct ContentView: View {
	@EnvironmentObject var gameSettings: GameSettings
	
	var body: some View {
		GeometryReader { geo in
			ZStack {
				HStack(spacing: 0.0) {
					RightView().environmentObject(gameSettings)
						.frame(width: geo.size.width / 2.0, height: geo.size.height)
					Spacer()
				}
				VStack {
					HStack {
						Spacer()
						Button {
							print("\(gameSettings.score)")
						} label: {
							Text("Print")
								.font(.largeTitle)
						}.padding(.trailing, 40.0)
					}
					Spacer()
				}
			}
		}
	}
}
Getting an Updated Value Through @EnvironmentObject
 
 
Q