Is it DrawableGameComponent the wrong tool for creating buttons?

时光毁灭记忆、已成空白 提交于 2019-12-24 21:17:15

问题


I am making a game based on Game State Managment pattern. I made 20 button on a 2nd page that let the user pick the level.

 LevelButton : TexturedDrawableGameComponent

Inside LoadContent() buttons are created and added to GameComponent collection. If I get this right the GameCompoenent is a sort of global collection, so when the user goes back from 4th page to 2nd app will add another 20 buttons.

I added a loop that clears all LevelButtons from the collection, but seems this is wrong.

Is it DrawableGameComponent the wrong tool for creating buttons?


回答1:


Yes.

DrawableGameComponent and its friends are optional bits of the XNA framework. Consider them helpers. Simple example implementations.

If you need more or different functionality to what they provide, you must replace them with your own implementation!

In this case it seems that what you want is a "Button" object (like your LevelButton), probably with methods like Update and Draw.

And then you want some kind of "Button Container" object that will hold all these buttons, and keep them drawn and updated when they are on-screen. But not do anything with them while they are off-screen.

(You could create your own instance of GameComponentCollection to manage this, and keep using game components. But you still have to provide your own draw/update/load/unload/initialise logic. The logic for Game.Components is internal to Game and not reusable. I recommend just using a List - keep it simple!)

The alternative to creating multiple collections - which is to add and remove (or disable/enable) components from the global collection - is horrifically ugly and error-prone. Don't do it.




回答2:


I think that it is not wrong if it runs.

Maybe you can approach this in several more elegant ways or improving the way you do it... but the matter is that it have to run.

Maybe you are trying to remove the button when you click it, this will give you problems because that button is being updated.

When the level selection screen becomes inactive or destroyed is the time to remove the buttons.

Of course, you can create a button collection class, that manages the list of buttons, and then you only have enable/disable or remove one DrawableGameComponent, and can be useful in other screens.



来源:https://stackoverflow.com/questions/9421275/is-it-drawablegamecomponent-the-wrong-tool-for-creating-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!