Custom Random Item Dropper
Customize a Random Item Dropper when selected rewards need per-instance values before spawning. The Version 1 CustomRandomAttackStatDropper sample selects weighted Items, customizes Attack on copied unique Items and uses the inherited pickup path. Health Potion can pass through unchanged while Iron Sword receives a random Attack; Gold uses a separate Currency dropper.
Prepare independent rewards
- Give Weapon an integer Item Attribute named
Attack. Create a mutable, unique Iron Sword with compatibleAttribute<int>values on its Definition’s Default Item and runtime Item. - Keep Health Potion outside that Attack path when it should remain unchanged.
- Create a reward Inventory with
ItemDrops, purpose Drop, before the dropper’sAwake. Populate it with at least one positive-weight Item. - Assign an Item or Inventory Pickup prefab and Drop Transform using Item and Currency Droppers.
Use only intended reward Items in the table; add filtering/restrictions before initialization when needed. Its weights are a snapshot built at Awake.
Configure selection and Attack
| Field | Default / setup |
|---|---|
| Inventory / Item Collection ID | Assign the source; ID defaults to ItemDrops, purpose Drop. |
| Drop Copies | On; keep enabled for reusable reward tables and independent customization. |
| Split Unique Items | On; keep independent unique results separate. |
| Allow Empty Drops | On; select the desired policy in the implementation below. |
| Min Amount / Max Amount | 1 / 2 weighted draws, inclusive. |
| Amount Probability Distribution | Empty gives a uniform draw count; its clamped curve output can choose within Min/Max. |
| Pick Up Prefab / Drop Transform / Drop Radius | Assign the prefab and transform; radius controls inherited horizontal placement. |
| Random Attack Multiplier Distribution | Assign a deliberate curve; its output directly multiplies base Attack. |
Health Potion amount 6 and Iron Sword amount 1 are selection weights: potion is six times as likely per draw. Draws use replacement, combining repeated selections before copy/split preparation. Amounts are weights rather than the quantity awarded by one draw.
Attack is calculated from the Definition Default Item, multiplied by the curve at uniformly sampled time 0..1, then rounded to an integer. Base Attack 20 becomes 16, 20 or 25 for curve outputs 0.8, 1 or 1.25. A straight 0.8→1.2 curve produces a linear multiplier range. The Attack curve output is used directly, so choose its complete value range intentionally.
Keep Drop Copies on: customize the prepared copy and retain source data as a reusable template. The dropper keeps the source collection contents. Project-specific rarity can use this customization point; choose rarity before applying its corresponding Attack curve.
Implement the customization
Get prepared results, apply Item-level overrides, then spawn. This example keeps empty-result and attribute-type handling explicit:
using Opsive.Shared.Utility;
using Opsive.UltimateInventorySystem.Core.AttributeSystem;
using Opsive.UltimateInventorySystem.Core.DataStructures;
using Opsive.UltimateInventorySystem.DropsAndPickups;
using UnityEngine;
public class RandomAttackItemDropper : RandomItemDropper
{
[SerializeField]
private AnimationCurve m_RandomAttackMultiplierDistribution;
private const string AttackAttributeName = "Attack";
public override void Drop()
{
var itemsToDrop = GetItemsToDrop();
if (!m_AllowEmptyDrops) {
var totalAmount = 0;
for (var i = 0; i < itemsToDrop.Count; i++) {
totalAmount += itemsToDrop[i].Amount;
}
if (totalAmount == 0) { return; }
}
AssignRandomAttack(itemsToDrop);
DropItemsInternal(itemsToDrop);
}
protected virtual void AssignRandomAttack(ListSlice<ItemInfo> itemInfos)
{
if (m_RandomAttackMultiplierDistribution == null) { return; }
for (var i = 0; i < itemInfos.Count; i++) {
var item = itemInfos[i].Item;
if (item == null ||
!item.HasAttribute(AttackAttributeName, false, false)) {
continue;
}
var defaultItem = item.ItemDefinition?.DefaultItem;
var baseAttack = defaultItem?.GetAttribute<Attribute<int>>(
AttackAttributeName);
var runtimeAttack = item
.GetAttribute<Attribute<int>>(
AttackAttributeName, false, false);
if (baseAttack == null || runtimeAttack == null) {
Debug.LogWarning(
$"{item.name} must expose {AttackAttributeName} as Attribute<int>.");
continue;
}
var multiplier = m_RandomAttackMultiplierDistribution
.Evaluate(Random.value);
var value = Mathf.RoundToInt(baseAttack.GetValue() * multiplier);
runtimeAttack.SetOverrideValue(value);
}
}
}
GetItemsToDrop() is public/virtual; DropItemsInternal() is protected/virtual. A separate customization method can be tested without spawning. Validate table entries, types and curves before the first roll.
An Item Pickup prefab creates one object per resulting ItemInfo; Inventory Pickup creates one object containing the result list. Inherited placement uses Drop Transform plus horizontal radius and one unit upward. This route uses Item Dropper directly; use Item Object Spawner for a known ItemInfo at an exact position.
For a separate Gold reward, assign a source Currency Owner with 10 Gold, Random Currency Dropper, Currency Pickup prefab and Drop Transform. Multipliers 0.5–1.5 scale the source to 50%–150%. Call both droppers once from confirmed enemy death and guard that gameplay transition against repeated calls.
Verify selection and ownership
In an isolated test scene:
- Set Drop Radius to
0and callRandom.InitState(12345)immediately beforeDrop(). - Record Definitions, amounts, Attack and positions. Reset identical source data, seed and call order; the results should match.
- Change the seed and verify every count remains within Min/Max and Attack follows the intended curve range.
- Across many distinct seeds, potions should trend toward six selections per sword. Confirm potions gain no Attack override and the source sword retains its original value.
- Collect Items/Gold and compare the exact amounts added once to Inventory/Currency.
Other users of Unity’s global random sequence can change deterministic results. Use a fixed seed for isolated tests; use project-owned randomness or saved resolved rewards for replayable production behavior.
| Symptom | Check |
|---|---|
| Roll cannot run | Positive initialized table, Min/Max, valid prefab and Drop Transform. |
| Attack is unchanged or has the wrong type | Mutable unique copy, Item-level Attribute<int>, Default Item base and multiplier curve. |
| Later rewards mutate the template | Keep Drop Copies enabled. |
| Unexpected empty pickup | Select the intended Allow Empty Drops policy in the override. |
| Edited weights are ignored | Reinitialize or explicitly rebuild the table. |
| Repeated test differs | Restore source data and keep random consumers/call order fixed. |
Use pickup success/fail/partial UnityEvents for collection feedback; creation feedback belongs around the owning gameplay call. Persistent unclaimed loot needs resolved Item data, amount, transform and runtime overrides saved explicitly. Inventory/Item Savers cover rewards after entering a saved Inventory. In multiplayer, roll/customize once on the authority and replicate resolved identity, Attack, amount and transform.
See Item Pickups, Attributes, Defining Attributes, Item Objects, Currency, Save System and Events.