Hmmm… let’s try making some adjustments to make sure that the default weapon is added to the Equipment…
In SetupDefaultWeapon()
private Weapon SetupDefaultWeapon()
{
equipment.AddItem(EquipLocation.Weapon, defaultWeapon); //this will trigger UpdateWeapon
}
and in UpdateWeapon()
{
var weapon = equipment.GetItemInSlot(EquipLocation.Weapon) as WeaponConfig;
if(weapon==null)
{
SetupDefaultWeapon();
}
else
{
EquipWeapon(weapon);
}
}
Now there is one problem with this approach… when you equip a new weapon, a copy of the default weapon will be added to the Inventory… If you then unequip the new weapon, yet another copy of the default weapon will be created in the Equipment… Certain weapons you really don’t want to wind up in inventory (Unarmed), and if you start the player with a rusty pocketknife, the player can create infinite copies…
For this, we’ll need to borrow an interface from the Shops and Abilities course, intended to allow us to pick up coins and have them deposited automagically in the Purse…
namespace GameDevTV.Inventories
{
public interface IItemStore
{
int AddItems(InventoryItem item, int number);
}
}
Next a small change to AddToFirstEmptySlot() in Inventory.cs:
public bool AddToFirstEmptySlot(InventoryItem item, int number)
{
foreach (var store in GetComponents<IItemStore>())
{
number -= store.AddItems(item, number);
}
if (number <= 0) return true;
int i = FindSlot(item);
if (i < 0)
{
return false;
}
slots[i].item = item;
slots[i].number += number;
if (inventoryUpdated != null)
{
inventoryUpdated();
}
return true;
}
And finally implementing the IItemStore Interface in Fighter.cs
public class Fighter: MonoBehavior, IAction, IItemStore
and to implement IItemStore
public int AddItems(InventoryItem item, int number)
{
return item == defaultWeapon ? 1 : 0;
}
So what this does is check to see if the item being added to Inventory (from the process of equipping another item or dragging the default weapon from Equipment into the inventory) is the default weapon. If it is the default weapon, then we just drop it from the transaction.
This means you’ll need to be careful about what you make as the default weapon. If it’s a sword you could otherwise find in the world, the player will get cranky if it dissappears. (IMO, the best starting weapon is always unarmed)