Factories

Introduction

The term "Factories" comes from the factory design pattern. Factories are objects which can create new instances of certain types of Entities. Factories provide the following benefits:

  1. Entities created in a factory will automatically be added to screen lists (by default).

  2. Factories provide a standard way to create entities which is especially useful for systems like Tiled to instantiate new entities.

  3. Factories can pool Entities which can greatly reduce allocated memory for Entities which are created and destroyed frequently.

If your game requires the creation of entities in code (such as the player shooting bullets or enemies appearing at an enemy spawn point), then you will want to use factories.

Factories Enabled by Default

When adding a new entity, the Create Factory checkbox is automatically checked. In most cases this should be left as true since most entities should be created by factories so they can be properly added to their corresponding lists (usually in GameScreen).

Quick Usage Example

As mentioned above, most of the time factories are added automatically when creating an Entity. To add a factory after-the-fact, see the CreatedByOtherEntities property on your Entity.

To use a factory in code, use the CreateNew method when you would like to create a new entity. For example, you can create a Player instance in the CustomInitialize of your screen as shown in the following code:

  1. void CustomInitialize()
    {
        var player = Factories.PlayerFactory.CreateNew(x: 50, y: 100);
        // perform any additional modifications to the player here
    }

Factories Generated by Glue

Glue will automatically generate factories for any entity which has its Created by Other Entities property set to true. For information on this property, see the CreatedByOtherEntities page.

Last updated