Assets are an essential part of most games, how you manage them determines whether you spend more time working on them than dealing with them.
For small to medium games, loading an entire directory and having it referenced to a Map is the ideal solution. It’s both flexible and simple.
The following code allows you to do just this:
Prototype.i LOAD_DIRECTORY_CALLBACK( Map Assets.i(), directory.s, extension.s, name.s, userDefined.i = #Null ) Procedure.i LoadDirectory( Map assets.i(), directory.s, extension.s, *callback.LOAD_DIRECTORY_CALLBACK, userDefined.i = #Null ) Define.i dir = ExamineDirectory( #PB_Any, directory, "*" + extension ) If IsDirectory( dir ) Define.i count = 0 Define.s name = "" While NextDirectoryEntry( dir ) If DirectoryEntryType( dir ) = #PB_DirectoryEntry_File name = DirectoryEntryName( dir ); assets( ReplaceString( name, extension, "" ) ) = *callback( assets(), directory, extension, name, userDefined );LoadSound( #PB_Any, directory + "\" + name ) count + 1 EndIf Wend FinishDirectory( dir ) EndIf ProcedureReturn count EndProcedure
To use this code you must define a procedure of your own, this procedure is going to be called on each file to be loaded; you’ll have to load and process the file in this function.
Global NewMap sprite.i() Procedure.i callback_loadsprites( Map Assets.i(), directory.s, extension.s, name.s, userDefined.i = #Null ) ProcedureReturn LoadSprite( #PB_Any, directory + "\" + name, userDefined ) EndProcedure LoadDirectory( sprite(), "sprites", ".png", @callback_loadsprites() )
The example will attempt to scan through the directory “sprites”, it will execute your callback on each png file it finds inside the aforementioned directory, furthermore it’ll reference the filename (without extension) to the sprite() Map, so when you need a handle for the sprite called “fire.png” you’d just use sprite(“fire”) to obtain it.
Since the files are referenced to a Map by their actual name, you could easily implement a scripting system or any other dynamic management solution for your assets without much hassle.
An interesting part of the code is the return value, it’s actually the number of assets found (not the ones loaded, since your callback could choose not to load a certain file, for instance).
There are several limitations to this simple implementation, which is why I mentioned “small games” – There is no directory recursion, no advanced filtering options, no way to parallel the process on a separate thread and there’s no error handling at the moment.
However, it’s still very useful and I highly recommend you try it out, while it’s not a novel aproach, it’s always been the method I used to load my assets and it just works.