I am just wondering what are some of the issues of loading and freeing the memory every time player changes the game state?

Or is it better to load all the resources at once?

  • 1
    \$\begingroup\$ What state? Do you have an issue that needs to be solved? \$\endgroup\$ – Vaillancourt Feb 1 '19 at 4:13
  • \$\begingroup\$ Generally, StackExchange Q&A is better at solving problems that users identify, than it is at predicting problems that have yet to occur. If you haven't run into any specific problems yet, then you're probably OK to proceed on your current course for now. You don't need us to tell you excess allocation/loading could be a potential risk - but whether that risk is a problem in your case is something your own testing will reveal with more confidence than our pontification. ;) So: what have your tests shown so far? If your profiling shows there's an issue, tell us about it and we'll help solve it. \$\endgroup\$ – DMGregory Feb 1 '19 at 5:40
  • \$\begingroup\$ This is simply a tradeoff of loading time vs. memory usage. The "better" solution depends on the specific use-case. \$\endgroup\$ – Philipp Feb 1 '19 at 9:34

The answer is game specific, and vastly depends on what you define as a "state". Does your game "change state" when moving from the main menu to the game itself? Then you should probably unload resources for the main menu and load ones meant for the game.

Does "game state" mean you moved from your game's "attack phase" to "defend phase" which have no new assets? Then probably you don't need to load or unload anything.

Here are some tips and things to remember:

  • Machines have plenty of memory, as in, if you want to keep an image loaded for a little longer than needed, its not the end of the world.
  • No matter what, do not attempt to load/unload assets every frame. It can only lead to disaster. If you need an asset every frame for as long as you are in the main menu, load it when the main menu starts, and unload it when you move to a different menu. If the asset is being used everywhere in the game, load it when the game starts, and unload it when the game ends.
  • Depending on the language, unloading assets could be handled by a garbage collector, so even if you think you've unloaded some assets, they could still be in memory, waiting the GC to delete them.
  • Loading assets means keeping the CPU busy for some time, do it only when you can afford that (like loading screens)
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.