codeAPI Reference

s&box AmmoInventory: Shared ammo pools

calendar_today May 12, 2026 schedule ~2 min read person PatrickJr verified 50

AmmoInventory Component API Reference

AmmoInventory stores shared ammo pools on a player, keyed by AmmoResource. Add this component to the player prefab alongside PlayerInventory to enable shared ammo across weapons.

Type Signature

CSHARP
public sealed class AmmoInventory : Component
{
    [Sync(SyncFlags.FromHost)] public NetDictionary<string, int> Pool { get; set; } = new();

    public int GetAmmo(AmmoResource resource);
    public void SetAmmo(AmmoResource resource, int value);
    public int AddAmmo(AmmoResource resource, int count);
    public bool TakeAmmo(AmmoResource resource, int count);
    public bool HasAmmo(AmmoResource resource, int count = 1);
}

Properties

Methods

GetAmmo(AmmoResource resource)

Returns the current ammo count for the given resource. Returns 0 if resource is null or not in pool.

SetAmmo(AmmoResource resource, int value)

Sets the ammo count for the given resource directly, clamped to [0, resource.MaxReserve]. Routes through RPC when called from a client.

AddAmmo(AmmoResource resource, int count)

Adds ammo to the pool for the given resource, clamped to max. Returns the actual amount added (optimistic when called from a client).

TakeAmmo(AmmoResource resource, int count)

Attempts to consume count ammo from the pool. Returns true and deducts the ammo if successful (optimistic when called from a client).

HasAmmo(AmmoResource resource, int count = 1)

Returns true if there is at least count ammo in the pool.

Behavior

  • Pool is synced from host to ensure server-side pickups replicate correctly
  • Client calls route through RPCs to the host for authoritative updates
  • All operations are clamped to the AmmoResource's MaxReserve value
  • Resource paths are used as dictionary keys

Usage

CSHARP
// Add to player prefab
var player = GameObject.AddComponent<Player>();
var ammoInventory = player.AddComponent<AmmoInventory>();

// Get ammo
int pistolAmmo = ammoInventory.GetAmmo(pistolResource);

// Add ammo
int added = ammoInventory.AddAmmo(pistolResource, 30);

// Take ammo
if (ammoInventory.TakeAmmo(pistolResource, 1))
{
    // Fire weapon
}

// Check ammo
if (ammoInventory.HasAmmo(pistolResource, 5))
{
    // Can fire 5 shots
}

// Set ammo directly
ammoInventory.SetAmmo(pistolResource, 50);

Notes

  • Must be added to player prefab alongside PlayerInventory
  • Uses AmmoResource.ResourcePath as the dictionary key
  • Host-authoritative design prevents client-side ammo cheating
  • Optimistic client returns for AddAmmo/TakeAmmo to avoid latency
Was this helpful?