Game Development Reference
In-Depth Information
There is quite a lot going on in the preceding code, so let's break it down. First, notice
that this class is using a design pattern called singleton . Simply put, a singleton class
ensures that only a single instance of it will exist; hence the name singleton. This
makes sense here because there is no reason to have multiple instances that point to
the same resources. A singleton is implemented by defining a private constructor
that prevents other classes from instantiating it. The instance variable holds the
actual instance of the class. It uses the public static final modifiers that allows
read-only access and is the one and only way to access this class. The staticness of
this class allows us to access it from virtually anywhere in the game code without
having to pass over its reference to every method where we will use it.
A singleton can be implemented to do either lazy or eager initialization.
Using lazy initialization means that the instance is created only when it
is requested for the very first time. Any subsequent requests will always
yield the exact same instance. In contrast, eager initialization means that
the instance is directly created on startup.
For more information, refer to the topic Design Patterns: Elements of
Reusable Object-Oriented Software , Erich Gamma , Richard Helm , Ralph
Johnson , and John Vlissides , Addison Wesley .
The init() method will be called at the very beginning when the game starts. It
will initialize the asset manager, which in turn will load all the assets. Loading the
assets using the asset manager is simply done by calling its load() method. The
method takes the path and filename as the first argument and the corresponding
class to instantiate as the second argument. The loading process is started by calling
finishLoading() . This is a blocking method that waits until all the assets are fully
loaded. After that, we always print the number of loaded assets and their names to
the console to easily check whether it is working the way we expect it to work.
The Assets class implements the Disposable and AssetErrorListener interfaces.
As we know that assets should always be unloaded when they are no longer needed,
we have implemented the dispose() method to delegate these requests to the asset
manager. The error() method will be called whenever an error has occurred in
the asset manager. However, before the asset manager calls our implementation
of the interface, it needs to be told about the class that implements the
AssetErrorListener interface by calling the asset manager's setErrorListener()
method. We are using the error() method to print error logs only to the console.
You could add additional code here to handle errors and therefore avoid the game
from crashing in this case.
 
Search WWH ::




Custom Search