Repository navigation
Items
Items are everything that fits in an inventory slot: weapons and tools, potions
and food, materials, and the blocks and furniture you place in the world. A mod
adds an item by writing a class that extends ModItem, and this page follows
such a class from its first lines to the hooks that run while the item is held
and used. Weapons, accessories and armor
and recipes build on what this page explains, and each of them has a
page of its own.
using Terraria;
using Terraria.ModLoader;
namespace MyMod.Content.Items;
public class ShinyRock : ModItem
{
public override void SetDefaults()
{
Item.width = 20;
Item.height = 20;
Item.maxStack = Item.CommonMaxStack;
Item.value = Item.buyPrice(silver: 1);
}
}maxStack starts at 1, as in tModLoader (the phone's game would start every
item at 9999): set it for anything that stacks.
The texture is Content/Items/ShinyRock.png: the namespace plus the
class name, as in tModLoader, and the first part (the mod's name) may be
missing on disk. Override Texture to use another path, or a game image as in
tModLoader: public override string Texture => "Terraria/Images/Item_" + ItemID.LastPrism;
(the same works for ModProjectile, ModBuff and ModNPC). A texture that
does not exist logs an error and the item or projectile draws a placeholder; the
rest of the mod still loads. The name and tooltip come from the mod's translations,
Localization/en-US_Mods.MyMod.hjson (see
Translations):
Items: {
ShinyRock: {
DisplayName: Shiny Rock
Tooltip: It glows a little
}
}
Nothing registers the class by hand: Bunny Loader finds it in your .dll.
ModContent.ItemType<ShinyRock>() is its item ID, and
ModContent.GetInstance<ShinyRock>() is the registered object (both are 0
and null for a class that did not load, as in tModLoader). A complete
example is samples/ExampleModCSharp, the
port of tModLoader's ExampleMod.
These run while a player holds or uses the item. Each one exists on
ModItem (for your item) and on GlobalItem (with the Item first, for any
item), with tModLoader's signatures:
ModItem |
When | Return |
|---|---|---|
CanUseItem(Player player) |
Before a use starts |
false stops it (every mod is asked; one false is enough) |
UseItem(Player player) |
The frame the use starts |
bool?: true makes it count as used (the use time is applied); null leaves it to the game |
UseAnimation(Player player) |
Before the game computes the animation length | change Item.useAnimation here to change it |
UseStyle(Player player, Rectangle heldItemFrame) |
Every frame of a use, after the game places the item | |
HoldStyle(Player player, Rectangle heldItemFrame) |
Every frame the item is held but not used | |
HoldItem(Player player) |
Every frame the item is in hand | |
HoldoutOffset() |
With the styles |
Vector2?: moves the item in the hand (x forward, y down) |
UpdateInventory(Player player) |
Every frame the item is in the inventory (the 58 slots, coins and ammo too) | |
UseTimeMultiplier(Player player), UseAnimationMultiplier(Player player), UseSpeedMultiplier(Player player)
|
When a use starts |
float: the use time is multiplied by UseTimeMultiplier, the animation by UseAnimationMultiplier, and both divided by UseSpeedMultiplier (the GlobalItems multiply in) |
CanAutoReuseItem(Player player) |
When the game decides whether the use repeats |
bool?: true repeats it even without autoReuse, false never |
AltFunctionUse(Player player) |
When the player uses the tile control (right click) with the item |
true: the item is used with player.altFunctionUse == 2 (check it in UseItem, CanUseItem, Shoot...) |
UseItemFrame(Player player) / HoldItemFrame(Player player)
|
Every frame, after the game picks the player's body frame, while the item is used / held | change player.bodyFrame
|
ModifyManaCost(Player player, ref float reduce, ref float mult) |
When the game checks or spends the mana of a use |
reduce starts at player.manaCost; the cost is the item's mana × reduce × mult (multiply mult) |
OnMissingMana(Player player, int neededMana) |
When the player has less mana than the use needs | |
OnConsumeMana(Player player, int manaConsumed) |
After the mana is spent |
ModifyResearchSorting(ref ContentSamples.CreativeHelper.ItemGroup itemGroup)
moves the item to another group of the Journey research list
(ExampleGolfBall sorts with the golf items).
Healing items (potions, food that heals) have their own:
ModItem |
When | Return |
|---|---|---|
GetHealLife(Player player, bool quickHeal, ref int healValue) |
When the item heals, and when the quick heal button picks the best potion | change healValue
|
GetHealMana(Player player, bool quickHeal, ref int healValue) |
When the item restores mana | change healValue
|
ModifyPotionDelay(Player player, ref int baseDelay) |
When a potion gives Potion Sickness | change the length, in ticks |
ApplyPotionDelay(Player player, int potionDelay) |
Right after |
false: no Potion Sickness this time |
quickHeal is true when the heal comes from the quick heal or quick mana
button.
Picking an item up from the ground:
ModItem |
When | Return |
|---|---|---|
CanPickup(WorldItem item, Player player) |
Before the player grabs the item |
false: it stays on the ground (the GlobalItems are asked first; one false is enough) |
GrabRange(WorldItem item, Player player, ref int grabRange) |
When the game measures how close the item has to be | change grabRange, in pixels; more pulls it from farther, less takes it only closer |
GrabStyle(WorldItem item, Player player) |
Every frame the item is pulled toward the player |
true: you moved it (change its WorldItem's velocity or position) and the game does not |
ItemSpace(Player player) |
When the inventory is full |
true: it is picked up anyway (pair it with OnPickup) |
OnPickup(WorldItem item, Player player) |
When the player touches the item |
false: the item leaves the ground and does not go into the inventory |
PostUpdate(WorldItem item) |
Every frame the item is on the ground, after the game moved it | Glow, dust, anything else: Lighting.AddLight(item.Center, ...)
|
An item on the ground is a WorldItem that holds the Item
(WorldItem.inner), as in tModLoader. The pickup hooks get it, with the position
and the velocity; Item.GetWorldItem() gives it from an Item (IsNull when
the item is not on the ground):
public override bool GrabStyle(WorldItem item, Player player)
{
Vector2 toPlayer = player.position - item.position;
item.velocity = toPlayer / Math.Max(1f, toPlayer.LengthValue) * 8f;
return true;
}ExampleResourcePickup is an item that never enters the inventory
(ItemID.Sets.IsAPickup): OnPickup fills the Example resource and returns
false, and ExampleResourcePickupGlobalNPC drops it. Item.NewItem also
takes a Rectangle, or a position and a size, to spawn at the middle of a box.
NPC.GetSource_Loot, Player.GetSource_Buff, GetSource_Accessory and
GetSource_Accessory_OnHurt are there as in tModLoader.
NPCID.Sets.NeverDropsResourcePickups is there for mods to read, as this
example does; the game's own hearts and stars on the phone do not check it.
Opening an item (a bag, a crate):
ModItem |
When | Return |
|---|---|---|
CanRightClick() |
When the game loads (for the touch "Open" button) and when the player opens it |
true: the item opens |
RightClick(Player player) |
When it opens: give the contents here (player.QuickSpawnItem) |
|
ConsumeItem(Player player) |
Right after |
false: the item is not spent |
The phone's game opens only the items in ItemID.Sets.OpenableBag: Bunny
Loader adds every item whose CanRightClick() returns true when the game
loads (asked on a fresh item of that type), so the "Open" button shows up for
it. A GlobalItem can do the same for a vanilla item, and its RightClick
also runs when a vanilla bag or crate opens (the game still gives what is
inside). A boss bag of yours (ItemID.Sets.BossBag) can also give a
developer set, as in tModLoader, unless you mark it pre-Hardmode in
SetStaticDefaults (ItemID.Sets.PreHardmodeLikeBossBag[Type] = true;, a
tModLoader set that Bunny Loader adds, with the game's pre-Hardmode bags
already marked). ModifyItemLoot uses the loot rules described under NPC loot
(ItemLoot, IItemDropRule).
The tooltip, as a list of TooltipLine:
public override void ModifyTooltips(List<TooltipLine> tooltips)
{
TooltipLine? damage = tooltips.Find(l => l.Mod == "Terraria" && l.Name == "Damage");
if (damage != null) damage.Text += " (charged)";
tooltips.Add(new TooltipLine(Mod, "Charge", $"Charge: {Charge}"));
}The game's lines have Mod "Terraria" and tModLoader's names
(ItemName, Damage, CritChance, Speed, Knockback, Defense,
Tooltip0, Tooltip1..., Material, PrefixDamage, SetBonus...).
Hide() takes a line out; IsModifier/IsModifierBad draw it in the green
or red of a prefix line. A GlobalItem gets ModifyTooltips(Item item, List<TooltipLine> tooltips) for any item, after the ModItem. OverrideColor (or Color, its short form) gives a line its own color, and
[c/RRGGBB:text] colors a part of a line (the phone's game has no such tags;
Bunny Loader draws them). [i:type] draws an item's icon; the phone's font
reads only that form, so [i/s123:1508] shows up as plain text.
Colors.PrefixGood and Colors.PrefixBad are the green and red of prefix
lines.
Drawing the tooltip yourself, as in tModLoader:
ModItem |
When | Return |
|---|---|---|
PreDrawTooltip(ReadOnlyCollection<TooltipLine> lines, ref int x, ref int y) |
Before the tooltip is drawn |
false: no line is drawn (the line hooks still run); change x/y to move it |
PreDrawTooltipLine(DrawableTooltipLine line, ref int yOffset) |
Before each line |
false: the line is not drawn; change line.X/Y, Color, Rotation, Origin, BaseScale, Spread; yOffset moves the lines below |
PostDrawTooltipLine(DrawableTooltipLine line) |
After each line | |
PostDrawTooltip(ReadOnlyCollection<DrawableTooltipLine> lines) |
After the tooltip |
The game still lays out the tooltip and draws its box; Bunny Loader steps
in when it draws each line's text. The phone's tooltip box has no item name:
the ItemName line is in the list for ModifyTooltips, but it is never
drawn, so the line hooks do not run for it. The price lines (shop, reforge), the
One Drop logo and the materials grid of the crafting guide are drawn by the
game without the line hooks.
Drawing the item:
ModItem |
When | Return |
|---|---|---|
GetAlpha(Color lightColor) |
Whenever the game asks the item's color (on the ground, in the inventory) |
Color?: the color to use; null leaves it to the game |
PreDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, ref float rotation, ref float scale, int whoAmI) |
Before the item on the ground is drawn |
false: the game does not draw it (draw it yourself); change rotation and scale to draw it differently |
PostDrawInWorld(SpriteBatch spriteBatch, Color lightColor, Color alphaColor, float rotation, float scale, int whoAmI) |
After it, also when PreDrawInWorld returned false
|
|
PreDrawInInventory(SpriteBatch spriteBatch, Vector2 position, Rectangle frame, Color drawColor, Color itemColor, Vector2 origin, float scale) |
Before the item's icon is drawn in a slot |
false: the game does not draw the icon |
PostDrawInInventory(...) |
After it, with the same arguments |
whoAmI is the item's index in Main.item. Color and SpriteBatch are in
Microsoft.Xna.Framework.Graphics (the phone's XNA keeps Color there).
The GlobalItems are asked first for GetAlpha (the first color wins) and
for PreDrawInInventory; for the others the ModItem goes first, as in
tModLoader.
A hook only costs anything when some mod overrides it: Bunny Loader hooks the
game method behind it the first time a loaded ModItem or GlobalItem
overrides that hook. An exception in a hook goes to the log once (not every
frame), and the game goes on as if the hook were not there.
public class Teal : ModRarity
{
public override Color RarityColor => new(0, 200, 200);
public override int GetPrefixedRarity(int offset, float valueMult) => offset < 0 ? ItemRarityID.Blue : Type;
}Item.rare = ModContent.RarityType<Teal>(); gives it to an item. The type
comes after the game's 12 (RarityLoader.VanillaCount). RarityColor is read each time the color is
drawn (it can blink with Main.DiscoR...). When a prefix changes how much
the item is worth, offset goes from -2 to +2 and GetPrefixedRarity
decides (the game alone would turn every rarity above 11 into purple). The
color shows on the text that rises when the item is picked up and on the
item's name under the cursor and in the tooltip.
public class Shiny : ModPrefix
{
public override PrefixCategory Category => PrefixCategory.Melee;
public override void SetStats(ref float damageMult, ref float knockbackMult, ref float useTimeMult, ref float scaleMult,
ref float shootSpeedMult, ref float manaMult, ref int critBonus)
{
damageMult *= 1.2f;
critBonus += 5;
}
public override void ModifyValue(ref float valueMult) => valueMult *= 1.1f;
}Category says which items can roll it (Melee, Ranged, Magic,
Summon, AnyWeapon, Accessory; Custom only where CanRoll or the
item lets it). RollChance is its weight against the game's prefixes (each
weighs 1). The game applies the stats (a prefix whose stats change nothing on
an item does not roll there), then Apply(Item item) runs;
ApplyAccessoryEffects(Player player) runs every frame while the accessory
is equipped, and GetTooltipLines(Item item) adds lines after the game's
prefix lines. The name comes from Mods.<Mod>.Prefixes.<Name>.DisplayName,
and the game writes it before the item's name, with a space. Prefix numbers
are saved by name, so they may change between sessions.
See Content/Prefixes in the Example Mod: ExamplePrefix scales by a Power
property, ExampleDerivedPrefix only overrides it, and ExampleAccessoryPrefix
gives defense from ApplyAccessoryEffects.
An item decides too: AllowPrefix(int pre), ChoosePrefix(UnifiedRandom rand) (a number forces that prefix), PrefixChance(int pre, UnifiedRandom rand) (false: no prefix; true: always one), and MeleePrefix(),
RangedPrefix(), MagicPrefix(), SummonPrefix(), WeaponPrefix() for
which of the game's prefixes it rolls (by default, from Item.melee,
ranged, magic, summon and noUseGraphic). A GlobalItem has the first
three, with the Item first.
| Member | What it does |
|---|---|
ModItem/GlobalItem.CanCatchNPC(target, player)
|
false forbids catching the NPC with this item, true allows it outside the game's tools, null keeps the game's rule. ItemID.Sets.CatchingTool[type] makes the item swing as a net |
ModItem.GetGolfClubProperties |
The club's shot. Use ItemID.Sets.IsAGolfClub[type]
|
ModItem/GlobalItem.OnSpawn(item, source)
|
An item enters the world, before it goes over the network |
ModItem/GlobalItem.UpdateVisibleAccessory, UpdateItemDye, UpdateInfoAccessory
|
A visible accessory, its dye and an information accessory, in the inventory too |
ItemLoader.RegisterUseStyle(mod, name) |
A new useStyle, handled by the UseStyle hook |
ModProjectile/GlobalProjectile.PrepareBombToBlow, DisplayDollSettings
|
The moment before an explosion, and the pose on a display doll |
ProjectileID.Sets.Explosive[type] |
The projectile follows the game's explosive rules. An aiStyle of 0 keeps your AI as the only one running |
ModPlayer.RefreshInfoAccessoriesFromTeamPlayers, EmitEnchantmentVisualsAt
|
Information shared by teammates, and enchantment visuals on a hitbox |
Item.StopAnimationOnHurt, Item.NetStateChanged()
|
The use ends when the player is hurt; sends the item's state again |
Player.ItemUsesThisAnimation, SetCCed(), MeleeEnchantActive, PotionDelayModifier
|
Shots of this use; crowd control until the next frame; a custom melee enchantment; the potion sickness time |
NPC.GravityMultiplier |
Set in a buff's Update; it returns to one every frame |
Chest.GetItem(slot), SetItem(slot, item)
|
A chest slot as an Item, with the mod's data |
BuilderToggle, InfoDisplay
|
New builder toggles and information lines; they appear below the game's own |
Main.instance.CameraModifiers.Add, Main.ParticleSystem_World_BehindPlayers.Add
|
Take a C# IModCameraModifier and a C# IModParticle; the game's own interfaces cannot be implemented from C# |
SoundEngine.PlaySound(style, position, callback), TryGetActiveSound
|
A sound you keep following while it plays |
ItemID.Sets.Factory and the factories of ProjectileID, NPCID, BuffID, TileID and WallID only cover mod content from SetStaticDefaults on. Create those sets there, not in a field initializer, since ReinitializeDuringResizeArrays does not exist here.
Not on the phone: ModItem.WingGlidingSpeeds, ArmorIDs.Head.Sets.IsTallHat and the PauseBehavior of a SoundStyle.
Bunny Loader wiki ·
Discord ·
Repository ·
BL Editor
Written for Bunny Loader 0.5.5-beta and Terraria Mobile 1.4.5.8.6.
Bunny Loader is not affiliated with Re-Logic or 505 Games.
