简体   繁体   English

你如何在 libgdx 中正确实现声音切换?

[英]How do you properly implement a sound toggle in libgdx?

I'm currently using a button in the main menu as a toggle that sets a boolean value to true or false.我目前使用主菜单中的按钮作为将布尔值设置为 true 或 false 的切换。 It's initialized to true and if it's set to false, no sound will play.它被初始化为 true,如果它被设置为 false,则不会播放任何声音。

However, the problem is that if you set the toggle to false in the main menu and switch screens to say, the play screen, and then back to the main menu again, it's initialized to true again because a new screen is being used.但是,问题是,如果您在主菜单中将切换设置为 false 并切换屏幕说播放屏幕,然后再次返回主菜单,则会再次初始化为 true,因为正在使用新屏幕。

What ways are there around this?有什么方法可以解决这个问题?

You need to store the value of the setting in a boolean field of a class instance that you keep around all the time.您需要将设置的值存储在始终保留的类实例的布尔字段中。 The button itself is a view object--do not rely on it to store your state.按钮本身是一个视图对象——不要依赖它来存储你的状态。

For example, create a class called UserSettings and have a soundEnabled boolean in it.例如,创建一个名为 UserSettings 的类并在其中包含一个soundEnabled布尔值。 Your game instance can keep a reference to an instance of UserSettings to pass to all the different screens.您的游戏实例可以保留对 UserSettings 实例的引用以传递到所有不同的屏幕。 When the MenuScreen is initialized, it looks at the soundEnabled boolean and uses that to set the initial checked state of the button.当 MenuScreen 初始化时,它查看soundEnabled布尔值并使用它来设置按钮的初始选中状态。 And the button has a ChangeListener that modifies the boolean in the UserSettings object appropriately.按钮有一个 ChangeListener 可以适当地修改 UserSettings 对象中的布尔值。

Then in the play screen, the same UserSettings object is passed in and that's what it uses to determine whether sound should be on.然后在播放屏幕中,传入相同的 UserSettings 对象,这就是它用来确定是否应该打开声音的内容。

Furthermore, you can save the UserSettings object to a file (or preference) using the Json class, and then your game can load the one from the file (if it exists) when the game is reopened.此外,您可以使用 Json 类将 UserSettings 对象保存到文件(或首选项),然后您的游戏可以在重新打开游戏时从文件(如果存在)加载该对象。 This way, the users' preferences are remembered from session to session.这样,用户的偏好会在会话之间被记住。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM