Note: This section is not necessary if you started with tutorial #1 after 12/10/2008

I want to post a little update I’ve made to the engine that doesn’t really need to be a tutorial itself. You don’t need to do this, but I’ve found that it can help with debugging later on. The problem I ran into several times is that I forgot that the engine had to be initialized before we could make components. This means that doing something like

public class Game1 : Game
{
	Actor actor = new Actor(...);

	public Game1()
	{
		.... and so on

would crash, because the engine had not set up its list of components in LoadContent() yet, and so was not ready to take new components. So, to remind myself not to do this, I added an exception that would be thrown if a component tried to set itself up before the engine was ready.

So, first we add a boolean to the Engine class called “Initialized”:

// Whether the engine has been initialized with SetupEngine()
public static bool IsInitialized = false;

Then set it to true at the end of the SetupEngine() method:

// Let components know the engine is ready to accept them
IsInitialized = true;

Now in the InitializeComponent() method of the Component class, we will first check if the engine has been intitialized, and if not we throw an exception to remind ourselves of this. Add this to the beginning of that method:

// Check if the engine has been initialized before setting
// up the component, or the Engine will crash when the
// component tries to add itself to the list.
if (!Engine.IsInitialized)
    throw new Exception("Engine must be initialized with "SetupEngine()""
        + "before components can be initialized");

Now, if we try to setup a component before the engine is ready, we will get a message telling us about it instead of a random crash. Note that something like this would still be fine:

public class Game1 : Game
{
	Actor actor;
	GraphicsDeviceManager graphics;

	public Game1()
	{
		graphics = new GraphicsDeviceManager(this);
	}

	protected override void LoadContent()
	{
		Engine.SetupEngine(graphics);

		actor = new Actor(...);
	}

	... and so on

« »