Tuesday, June 19, 2012

Platformer Kit: SPG_InventoryManager class (UnrealScript)

The SPG_InventoryManager class exists to allow the creation of inventory items based on Archetypes. In the Platformer Kit it is used to create the weapon of the player.

The class code is below:
class SPG_InventoryManager extends InventoryManager;

simulated function Inventory CreateInventoryArchetype(Inventory NewInventoryItemArchetype, optional bool bDoNotActivate)
    local Inventory    Inv;
    // Ensure the inventory archetype is valid
    if (NewInventoryItemArchetype != None)
        // Spawn the inventory archetype
        Inv = Spawn(NewInventoryItemArchetype.Class, Owner,,,, NewInventoryItemArchetype);
        // Spawned the inventory, and add the inventory
        if (Inv != None && !AddInventory(Inv, bDoNotActivate))
            // Unable to add the inventory, so destroy the spawned inventory
            Inv = None;

    // Return the spawned inventory
    return Inv;

    // Create the pending fire array

The CreateInventoryArchetype() function is called from the SPG_GameInfo class. It uses the Spawn() function to create an instance of the Inventory class based on the Archetype  received as parameter.

The Spawn() function is defined in the Actor class and has the following parameters:
native noexport final function coerce actor Spawn
    class<actor>      SpawnClass,
    optional actor    SpawnOwner,
    optional name     SpawnTag,
    optional vector   SpawnLocation,
    optional rotator  SpawnRotation,
    optional Actor    ActorTemplate,
    optional bool     bNoCollisionFail

Once created the instance of Inventory, it is added to the player's inventory through the AddInventory() function. You can find the code of this function in my article "PickupFactory and Inventory in UnrealScript".

If for some reason it is not possible to add the Inventory, the Destroy() function should be called to remove the object from memory. The Destroy() function is not executed immediately, so you need to assign "None" to the variable after the call to the Destroy() function.