Skip to content

Players

JonataOliveiraa edited this page Nov 14, 2026 · 1 revision
Basics

ModPlayer is how a mod attaches its own data and behavior to each player: a counter, a flag that an accessory turns on, extra life regeneration, something that happens when the player gets hurt. Every player in the world gets one instance of each ModPlayer class in your mod, and the game calls its hooks at the right moments of that player's life.

public class ExampleLuckPlayer : ModPlayer
{
    public override void ModifyLuck(ref float luck)
    {
        if (Main.hardMode) luck += 0.5f;
    }
}

Each ModPlayer class gets one instance per player, made the first time something asks for it (Initialize runs then), with Player set to that player. From anywhere: player.GetModPlayer<ExampleLuckPlayer>(), player.TryGetModPlayer(out ExampleLuckPlayer luck) or player.ModPlayers. Fields are per player, so keep the state there and reset what an effect turns on in ResetEffects.

The hooks so far, with tModLoader's signatures, each installed only when a loaded ModPlayer overrides it:

Hook When
ResetEffects, ModifyMaxStats(out health, out mana) after the game's Player.ResetEffects; the max stats are tModLoader's StatModifiers applied to statLifeMax/statManaMax and added to statLifeMax2/statManaMax2 (the saved base is not touched)
PreUpdate, PostUpdate around Player.Update
PreUpdateBuffs, PostUpdateBuffs around Player.UpdateBuffs
UpdateEquips, PostUpdateEquips after Player.UpdateEquips; after the armor sets (UpdateArmorSets)
UpdateBadLifeRegen, UpdateLifeRegen before and after Player.UpdateLifeRegen
PreModifyLuck(ref luck), ModifyLuck(ref luck) around Player.RecalculateLuck; false skips the game's luck
FrameEffects after the drawn slots are set (PlayerFrame)
UpdateDead after Player.UpdateDead
PreKill, Kill around Player.KillMe (not in god mode); false keeps the player alive. playSound and genDust are not used yet
OnEnterWorld, OnRespawn after Player.Hooks.EnterWorld; after Player.Spawn when the player was dead, as in tModLoader
CanUseItem(item) before the item's own CanUseItem
ResetInfoAccessories after ResetEffects, and after Player.RefreshInfoAccs
PreUpdateMovement once per update, before the first of the game's collision steps (wet, dry, sloping, borders), not when dead
PostUpdateMiscEffects after Player.CapAttackSpeeds
PostUpdateRunSpeeds before Player.HorizontalMovement
NaturalLifeRegen(ref float regen) inside Player.UpdateLifeRegen, on the natural regen value (a native hook in the middle of the method)
UpdateDyes, UpdateVisibleAccessories, UpdateVisibleVanityAccessories after Player.UpdateDyes; after Player.UpdateVisibleAccessories (the phone does both kinds in one method)
UpdateAutopause after Main.DoUpdate_WhilePaused, for the local player
ProcessTriggers(TriggersSet triggersSet) after TriggersSet.CopyInto for the local player
ArmorSetBonusActivated, ArmorSetBonusHeld(int holdTime) after Player.KeyDoubleTap/KeyHoldDown on the set bonus key (down, or up with Main.ReversedUpDownArmorSetBonuses)
OnEquipmentLoadoutSwitched(int oldLoadoutIndex, int loadoutIndex) after Player.TrySwitchingLoadout changed the loadout
SaveData, LoadData, PreSavePlayer, PostSavePlayer, PreSaveCustomData the character's <file>.plr.bl.json, under <mod uid>/<class>

The item hooks run inside the same game points as the ModItem ones, in tModLoader's CombinedHooks order: the item and its globals first, then the player, except CanShoot, Shoot, CanConsumeAmmo, OnConsumeAmmo, ApplyPotionDelay, CanUseItem and CanAutoReuseItem, where the player comes first. A ModPlayer hook covers every item, the game's included.

Hook When
PreItemCheck, PostItemCheck around Player.ItemCheck; false skips the game's item use for the frame
ModifyWeaponDamage, ModifyWeaponCrit, ModifyWeaponKnockback, ModifyItemScale, MeleeEffects as the item's
UseTimeMultiplier, UseAnimationMultiplier, UseSpeedMultiplier, CanAutoReuseItem multiplied with the item's
ModifyManaCost(item, ref reduce, ref mult), OnMissingMana, OnConsumeMana as the item's
GetHealLife, GetHealMana, ApplyPotionDelay as the item's
CanShoot, ModifyShootStats, Shoot, CanConsumeAmmo, OnConsumeAmmo as the item's
CanHitNPC(target), CanHitNPCWithItem, CanMeleeAttackCollideWithNPC an item's melee hit; CanHitNPC false refuses every hit of this player
ModifyHitNPC, ModifyHitNPCWithItem, OnHitNPC, OnHitNPCWithItem an item's melee hit, after the item's hooks
OnHitAnything(x, y, victim) after the game's Player.OnHit

ModPlayer in multiplayer

As in tModLoader, ExampleStatIncreasePlayer:

public override void SyncPlayer(int toWho, int fromWho, bool newPlayer)
{
    ModPacket packet = Mod.GetPacket();
    packet.Write((byte)ExampleMod.MessageType.ExampleStatIncreasePlayerSync);
    packet.Write((byte)Player.whoAmI);
    packet.Write((byte)exampleLifeFruits);
    packet.Write((byte)exampleManaCrystals);
    packet.Send(toWho, fromWho);
}

public override void CopyClientState(ModPlayer targetCopy) =>
    ((ExampleStatIncreasePlayer)targetCopy).exampleLifeFruits = exampleLifeFruits;

public override void SendClientChanges(ModPlayer clientPlayer)
{
    if (exampleLifeFruits != ((ExampleStatIncreasePlayer)clientPlayer).exampleLifeFruits)
        SyncPlayer(toWho: -1, fromWho: Main.myPlayer, newPlayer: false);
}
Hook When
SyncPlayer(toWho, fromWho, newPlayer) after the game's NetMessage.SyncOnePlayer (newPlayer the first time for that slot), and on the client right after it enters the world (toWho -1, newPlayer true)
CopyClientState(targetCopy) when the game copies the local player (Player.clientClone)
SendClientChanges(clientPlayer) every client update, with the copy from the last one
PlayerConnect(), PlayerDisconnect() on the server when a player joins or leaves (also when the slot just goes empty)

The phone's host plays in the same game: its Main.netMode is 3, so it is both a client ((Main.netMode & 1) != 0, it runs SendClientChanges) and the server ((Main.netMode & NetmodeID.Server) != 0). Code from tModLoader that tests Main.netMode == NetmodeID.Server to pass a packet on to the other clients has to use the & form, as the ExampleMod's HandlePacket does.

The mod compiler warns about these tests (BL0001). A test that means "I am the server" has to change. A test that means "I do not render", such as if (Main.netMode != NetmodeID.Server) around gore or dust, is fine as it is, because the host renders.

Getting hurt: Player.HurtModifiers and HurtInfo

public class ExampleImmunityPlayer : ModPlayer
{
    public bool HasExampleImmunityAcc;

    public override void ResetEffects() => HasExampleImmunityAcc = false;

    public override void PostHurt(Player.HurtInfo info)
    {
        if (HasExampleImmunityAcc && !info.PvP) Player.AddImmuneTime(info.CooldownCounter, 60);
    }
}

The hurt hooks run around the game's Player.Hurt, so every hit is seen: an NPC's, a projectile's (its index is in the PlayerDeathReason), a fall, lava, a debuff.

Hook When
ImmuneTo(damageSource, cooldownCounter, dodgeable) first; true skips the hit
CanBeHitByNPC(npc, ref cooldownSlot), CanBeHitByProjectile(proj) when the hit comes from an NPC or a projectile; false skips it
ModifyHitByNPC, ModifyHitByProjectile, then ModifyHurt(ref modifiers) on tModLoader's Player.HurtModifiers
FreeDodge(info), ConsumableDodge(info) for a dodgeable hit on the local player; true skips it
OnHitByNPC, OnHitByProjectile, OnHurt(info) after the game applied the hit, with the damage it took
PostHurt(info) after that, if the player is still alive

HurtModifiers does tModLoader's math: SourceDamage and IncomingDamageMultiplier act before the defense, ArmorPenetration, ScalingArmorPenetration, FinalDamage and SetMaxDamage after it, and Cancel() skips the hit. The game still does the rest of its Hurt (the crit of the phone's Hurt, endurance, the beetle and paladin's shield reductions), and HurtInfo.Damage in OnHurt is what it took. Not used yet: Knockback, KnockbackImmunityEffectiveness, HitDirectionOverride only changes the direction passed to the game, and DisableDust and DisableSound have no effect.

PvP

Hook Where it runs
ModItem.CanHitPvp(player, target), GlobalItem.CanHitPvp, ModPlayer.CanHitPvp(item, target) on the attacker, for each player its melee swing touches; false skips that player
ModItem.ModifyHitPvp(player, target, ref modifiers), GlobalItem.ModifyHitPvp on the victim's own game, before its ModifyHurt
ModItem.OnHitPvp(player, target, hurtInfo), GlobalItem.OnHitPvp on the victim, after the hit, with the damage it took
ModPlayer.CanHitPvpWithProj(proj, target) on the game that applies a PvP projectile hit, for the projectile's owner

The weapon is the one in the attacker's hand: the game's death reason only carries its type and prefix, so the Bunny Loader sends the attacker's item data (its NetSend, or its SaveData without one, and the globals' NetSend) right before the game's hurt message, and the victim's ModifyHitPvp/OnHitPvp see a copy with that data. The attacker's own copy of the victim takes the game's damage, as in the base game.

In the world: pickups, slots, shops, the nurse, critters

Hook When
OnPickup(WorldItem item) before Player.PickupItem; false destroys the item on the ground (TurnToAirAndSync), as in tModLoader
CanBeTeleportedTo(teleportPosition, context) before Player.Teleport ("TeleportRod" for style 1, "TeleportationPotion" for 2, "Teleport" for the rest) and UnityTeleport ("Wormhole"); false keeps the player in place
HoverSlot(inventory, context, slot) in ItemSlot.OverrideHover for the local player; true skips the game's cursor choice (set Main.cursorOverride with CursorOverrideID)
ShiftClickSlot(inventory, context, slot) in ItemSlot.OverrideLeftClick while ItemSlot.ShiftInUse; true skips the game's click
CanBuyItem, PostBuyItem(vendor, shopInventory, item) a purchase in ItemSlot.HandleShopSlot; false blocks it; item is the one now on the cursor
CanSellItem, PostSellItem(vendor, shopInventory, item) around Player.SellItem while talking to a vendor
ModifyNurseHeal(nurse, ref health, ref removeDebuffs, ref chatText) before the nurse's price and heal; false shows chatText and heals nothing
ModifyNursePrice(nurse, health, removeDebuffs, ref price) after Main.GetNurseHealCost
PostNurseHeal(nurse, health, removeDebuffs, price) after a paid heal
CanCatchNPC(target, item), OnCatchNPC(npc, item, failed) a bug net swing (ItemCheck_CatchCritters) or NPC.CatchNPC; true catches, false refuses; failed is true when the critter hurt the player instead
AddStartingItems(mediumCoreDeath), ModifyStartingInventory(itemsByMod, mediumCoreDeath) a new character (GUIPlayerCreateMenu.SetupStartingItems) and a mediumcore death (Player.DropItems); the game's items are under "Terraria", each mod's under its Name; what does not fit in the 50 slots goes to GetOrDropItem

The arrays are copies: changing inventory[slot] to another Item puts it back in the game's array after the hook. new Item(type, stack, prefix) makes a new item, as in tModLoader.

public class ExampleInventoryPlayer : ModPlayer
{
    public override IEnumerable<Item> AddStartingItems(bool mediumCoreDeath)
    {
        if (mediumCoreDeath)
            return [new Item(ItemID.HealingPotion)];
        return [new Item(ModContent.ItemType<ExampleItem>()), new Item(ItemID.GoldOre, 256)];
    }

    public override void ModifyStartingInventory(IReadOnlyDictionary<string, List<Item>> itemsByMod, bool mediumCoreDeath)
    {
        itemsByMod["Terraria"].RemoveAll(item => item.type == ItemID.IronAxe);
    }
}

On the phone, ItemSlot.ShiftInUse does not read ItemSlot.ShiftForcedOn.

Fishing

Hook When
GetFishingLevel(fishingRod, bait, ref fishingLevel) after Player.GetFishingConditions; fishingLevel is the level multiplier (LevelMultipliers), as in tModLoader, and FinalFishingLevel is worked out again from it
ModifyFishingAttempt(ref attempt) before Projectile.FishingCheck_ProbeForQuestFish, with the drop levels rolled; rolledItemDrop and rolledEnemySpawn are put back
CatchFish(attempt, ref itemDrop, ref npcSpawn, ref sonar, ref sonarPosition) after FishingCheck_RollItemDrop; a sonar.Text shows with the Sonar Potion
ModifyCaughtFish(fish) in AI_061_FishingBobber_GiveItemToPlayer, before the fish goes to the player
CanConsumeBait(bait) when the bobber uses the bait; false keeps it, true always uses it, null lets the game roll
AnglerQuestReward(rareMultiplier, rewardItems) after Player.GetAnglerReward, with the game's rewards in the list; the list is what the player gets
GetDyeTraderReward(rewardPool) in Player.GetDyeTraderReward, on the pool the dye comes from

The rod itself can move the line's start and color: ModItem.ModifyFishingLine(bobber, ref lineOriginOffset, ref lineColor) (the offset is from the player's center, mirrored when facing left), and a bobber can do the same with ModProjectile.ModifyFishingLine(ref lineOriginOffset, ref lineColor). The ExampleMod's ExampleFishingRod casts three to five ExampleBobbers, each with its own line color, synced with SendExtraAI.

PlayerFishingConditions on the phone has the types (PoleItemType, BaitItemType), not tModLoader's Pole/Bait items.

public class ExampleFishingPlayer : ModPlayer
{
    public bool hasExampleCrateBuff;

    public override void ResetEffects() => hasExampleCrateBuff = false;

    public override void ModifyFishingAttempt(ref FishingAttempt attempt)
    {
        if (hasExampleCrateBuff && !attempt.crate && Main.rand.Next(100) < 10)
            attempt.crate = true;
    }
}

Angler quests

An item becomes one of the Angler's daily fish with three ModItem hooks, as in tModLoader:

Hook What it does
IsQuestFish() true adds the item to the end of Main.anglerQuestItemNetIDs
IsAnglerQuestAvailable() false makes the daily swap pick another fish (for example, only in hardmode)
AnglerQuestChat(ref description, ref catchLocation) the Angler's text, shown as description and then (catchLocation)

GlobalItem.IsAnglerQuestAvailable(type) and GlobalItem.AnglerChat(type, ref chat, ref catchLocation) do the same for any fish, the game's included. The Angler uses the mod's text only when both strings are set. The fish itself is caught in ModPlayer.CatchFish when attempt.questFish is that item. The ExampleMod's ExampleQuestFish is caught in water while standing upside-down (ExampleFishingPlayer).

Extra jumps: ExtraJump

An ExtraJump is a double jump: the game's ones are ExtraJump.CloudInABottle, SandstormInABottle, BlizzardInABottle, FartInAJar, TsunamiInABottle, UnicornMount, SantankMount, GoatMount, BasiliskMount and Flipper. A mod adds its own as in tModLoader, and turns it on each frame with player.GetJumpState<T>().Enable():

public class SimpleExtraJump : ExtraJump
{
    public override Position GetDefaultPosition() => new After(BlizzardInABottle);

    public override float GetDurationMultiplier(Player player) => 2.25f;

    public override void UpdateHorizontalSpeeds(Player player)
    {
        player.runAcceleration *= 1.75f;
        player.maxRunSpeed *= 2f;
    }
}

public override void UpdateAccessory(Player player, bool hideVisual) =>
    player.GetJumpState<SimpleExtraJump>().Enable();

GetDefaultPosition puts it before or after one of the game's jumps, and GetModdedConstraints orders it among the mods' jumps there (ExtraJumpLoader.OrderedJumps). GetJumpState of a game jump reads and writes the game's own fields (hasJumpOption_*, canJumpAgain_*, isPerformingJump_*), so Enable(), Disable() and Available work on them too. Also there: player.ExtraJumps, blockExtraJumps, AnyExtraJumpUsable(), StopExtraJumpInProgress(), ConsumeAllExtraJumps().

Hook When
ModifyExtraJumpDurationMultiplier(jump, ref duration) when a jump starts; the jump time is Player.jumpHeight * duration, for the game's jumps too
CanStartExtraJump(jump) before a jump starts in the air; false skips it and leaves it available
OnExtraJumpStarted(jump, ref playSound) after it starts; playSound = false silences it (the game's jump sounds as well)
OnExtraJumpEnded(jump) when it stops (CancelAllJumpVisualEffects, or when it is disabled mid-jump)
OnExtraJumpRefreshed(jump) when the jumps come back (RefreshDoubleJumps, on the ground)
ExtraJumpVisuals(jump), CanShowExtraJumpVisuals(jump) in DoubleJumpVisuals; false hides the jump's effects
OnExtraJumpCleared(jump) when an available jump is taken away (unequipped in the air, a mount that blocks jumps, ConsumeAllExtraJumps)

Extra crafting materials

AddMaterialsForCrafting(out ItemConsumedCallback itemConsumedCallback) returns items the player can craft with as if they were in a nearby chest; the callback runs for each of them that a craft used, with its index in what the hook returned:

public class BagPlayer : ModPlayer
{
    public Item[] Bag = { new Item(ItemID.Ruby, 5) };

    public override IEnumerable<Item> AddMaterialsForCrafting(out ItemConsumedCallback itemConsumedCallback)
    {
        itemConsumedCallback = (item, index) => Main.NewText($"slot {index}: {item.stack} left");
        return Bag;
    }
}

The items stay the mod's: when a craft uses one up, the same Item turns to air instead of being replaced. The rest of tModLoader's ModPlayer (the projectile hits) comes with the projectiles.


← Buffs  ·  Tiles →

Clone this wiki locally