Yesterday I added a screen component class to our XNA libraries that's analogous to XNA's own game component class. The difference is obvious: screen components only exist and should be updated, drawn etc. when the screen is active instead of the game loop.
Arguably you could just use the Enabled and Visible properties in DrawableGameComponent. However, I think the clear separation makes the code easier to understand and it automates the calling of critical methods like Draw and Update within a single screen's loop.
The issue that arises is concerned with screen components that are dynamically added during the game runtime. Due to the fact that some screen components are created by other screen components during updates, when to actually add those newly-created objects to a screen's collection of components is slightly tricky. It comes down, I think, to a single consideration - do you want newly-created screen components to be updated during the same update loop in which they are created? My initial answer was no, partly because I was using iterators to traverse the component collection and the iterators would naturally get invalidated if I tried to modify the collection during the traversal. So instead I hid the raw collection and made AddComponent and RemoveComponent that would modify temporary lists. At the start of the next Screen.Update call, before the components themselves were updated, the lists of objects to add and remove would be combined with the main collection, and iterator-based traversal could continue as normal.
No comments:
Post a Comment