Unequipping / destroying weapon when its out of ammo

jackmerrill

New member
Hey there! I'm trying to use the UFPS kit and I'm having trouble detecting when the current/dominant weapon is out of ammo.

Currently I have this code for an Ammo Watcher script on the Character:

C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Opsive.Shared.Events;
using Opsive.UltimateCharacterController.Character;
using Opsive.UltimateCharacterController.Character.Abilities.Items;
using Opsive.Shared.Inventory;
using Opsive.UltimateCharacterController.Inventory;
using Opsive.UltimateCharacterController.Items;
using Opsive.UltimateCharacterController.Items.Actions;

public class AmmoWatcher : MonoBehaviour
{
    private Item m_Item;

    public void Awake()
    {
        EventHandler.RegisterEvent<Item, int>(gameObject, "OnAbilityWillEquipItem", OnEquip);
        EventHandler.RegisterEvent<Item, bool>(gameObject, "OnItemUpdateDominantItem", OnUpdateDominantItem);
    }

    private void OnEquip(Item item, int slotID)
    {
        m_Item = item;
        Debug.Log(item);
    }

    private void OnUpdateDominantItem(Item item, bool dominantItem)
    {
        Debug.Log("update");

        var action = item.ItemActions[0];

        Debug.Log(action);

        if (action is IUsableItem)
        {
            var usableItem = action as IUsableItem;

            Debug.Log(usableItem);
            Debug.Log(usableItem.GetConsumableItemIdentifierAmount());

            if (m_Item.ItemIdentifier == usableItem.GetConsumableItemIdentifier())
            {
                var ammo = usableItem.GetConsumableItemIdentifierAmount();

                if (ammo <= 0)
                {
                    m_Item.Unequip();
                    Debug.Log("unequipped");
                }
            }
        }
    }

    public void OnDestroy()
    {
        EventHandler.UnregisterEvent<Item, bool>(gameObject, "OnItemUpdateDominantItem", OnUpdateDominantItem);
    }
}

So far, it only logs the item that is equipped. Is this the best way to detect ammo changes, and if not, what is? If it is, what am I doing wrong? (I based this script off the SlotItemMonitor.cs script a bit)

Thanks!
 
Instead of OnItemUpdateDominantItem you should use OnInventoryAdjustItemIdentifierAmount:

 
Instead of OnItemUpdateDominantItem you should use OnInventoryAdjustItemIdentifierAmount:

That’s odd, I tried using that earlier and it didn’t work; I was checking if the Item Identifier matched with the Equipped Item’s identifier and it never went through.
 
Back
Top