Repository navigation
NPCs
NPCs are every creature in the game that is not a player: enemies and critters,
bosses, and the town NPCs who live in your houses. A mod adds new ones with
ModNPC and changes the existing ones with GlobalNPC. This page covers both,
from the basic numbers to AI, hits, loot, spawning and the Bestiary.
Bosses and Town NPCs have pages of their own for what is
specific to them.
A ModNPC registers a new NPC type after the game's types. Its texture and
display name follow the same conventions as items:
using Terraria;
using Terraria.ModLoader;
namespace MyMod.Content.NPCs;
public class FloatingFriend : ModNPC
{
public override void SetDefaults()
{
NPC.width = 24;
NPC.height = 26;
NPC.lifeMax = 120;
NPC.friendly = true;
NPC.noGravity = true;
NPC.noTileCollide = true;
NPC.aiStyle = -1;
}
}The texture is Content/NPCs/FloatingFriend.png, and the name is
Mods.MyMod.NPCs.FloatingFriend.DisplayName in the localization files.
ModContent.NPCType<FloatingFriend>() gives the type,
NPCLoader.GetNPC(type) and ModContent.GetModNPC(type) give the registered
template, and ModContent.Find<ModNPC>("MyMod/FloatingFriend") finds it by name.
NPCLoader.NPCCount includes every registered type; the game tables have that size by SetStaticDefaults.
The template has a real NPC in SetStaticDefaults, and its NPC.ModNPC is
the template itself. AutoStaticDefaults assigns TextureAssets.Npc[Type]
before that method. Set Main.npcFrameCount[Type] there for a sprite sheet;
TextureAssets.Npc exposes Asset<Texture2D> entries, including a setter.
Each NPC.SetDefaults creates a new mod instance. Read it through
npc.ModNPC; it stays the same until the object receives new defaults.
Constructor fields start fresh unless CloneNewInstances is true, in which
case Clone(newEntity) copies the template. ModNPC.NPC is a ref property,
so assignments to the pointer struct work as they do on tModLoader's class.
The instances use the same weak-handle storage as items and do not keep game
objects alive.
NPC.CloneDefaults(type) copies another type's defaults, including its mod
and globals, at Classic difficulty and scale 1. It restores the receiving
NPC's type, net ID, mod instance, globals and player interaction flags. The
outer defaults apply the requested difficulty once; NPCSpawnParams size
and difficulty overrides also work for mod NPCs. SetDefaults(type) and
SetDefaultsKeepPlayerInteraction(type, spawnParams) are available. The
game's NPC.Clone() also clones mod and per-entity global state; override
Clone to copy reference fields such as lists.
A GlobalNPC uses the same InstancePerEntity, AppliesToEntity, cloning
and instance-field validation as GlobalItem. Its hooks currently available
are SetStaticDefaults and SetDefaults(NPC entity). For each defaults run:
- Globals that apply with
lateInstantiation == falseare attached. - The
ModNPC.SetDefaultsruns, then those globals'SetDefaults. - The remaining globals are checked with
lateInstantiation == trueand attached, then theirSetDefaultsrun.
Use npc.GetGlobalNPC<T>(), GetGlobalNPC(baseInstance),
TryGetGlobalNPC(out T value), TryGetGlobalNPC(baseInstance, out T value)
or npc.EntityGlobals. A global without InstancePerEntity is shared;
per-entity globals are reset even when the game reuses the same NPC object.
For vanilla NPCs the hooks run after the game's type-specific defaults and
before its final frame, size and difficulty calculations. Changes to
buffImmune also survive the mobile game's later immunity initialization.
For C# mod NPCs the final difficulty scaling runs after all the defaults hooks.
NPC.NewNPC(default, x, y, type) uses this path too. The initial
PartyZombie port demonstrates registration, frame count, texture and base
stats. It now also borrows zombie AI and animation through AIType and
AnimationType, uses NPCAIStyleID.Fighter, and has the vanilla hit/death
sounds. It shares the zombie banner through Banner and BannerItem (see
Enemy banners). The rest of this page goes through
everything else an NPC can do: its AI, being hit, multiplayer, the bestiary,
contact damage, loot, spawning, buff immunity and its own saved data.
ModNPC and GlobalNPC support the following lifecycle hooks. A global's
signature has an NPC npc parameter before the parameters shown below.
| Hook | Behavior |
|---|---|
PreAI() |
All applicable globals run first, combining their results. The mod NPC runs only if all globals allow it. Returning false skips vanilla AI and the AI hooks. |
AI() |
Runs after vanilla AI: mod NPC first, then globals. |
PostAI() |
Mod NPC first, then globals, including when PreAI returned false. |
FindFrame(int frameHeight) |
Runs after vanilla framing: mod NPC first, then globals. frameHeight comes from the NPC's own sprite sheet and frame count. |
ResetEffects() |
Runs after vanilla buff flags are reset and before buffs are applied. Reset temporary fields belonging to the mod here. |
CheckActive() |
Returning false skips despawning and nearby NPC slot counting. Vanilla guards, including town NPCs and entities that do not despawn, run first. The mod NPC can stop the global checks; globals stop at the first false. |
CheckDead() |
All applicable callbacks run even after a false result. Any false stops death. Vanilla body-part guards and special boss phase transitions run before this point. |
HitEffect(NPC.HitInfo hit) |
Runs after vanilla hit effects, mod NPC first and then globals. |
UpdateLifeRegen(ref int damage) |
Changes NPC.lifeRegen and the damage batch used for damage-over-time text and health loss. Mod NPC first, then globals. |
OnSpawn(IEntitySource source) |
Runs once after NPC.NewNPC has set position, AI slots and target. Mod NPC first, then globals. SetDefaults by itself does not call it. |
ApplyDifficultyAndPlayerScaling(int numPlayers, float balance, float bossAdjustment) |
Runs in expert-or-higher scaling, after difficulty changes and before the final player-count life multiplier. Mod NPC first, then globals. |
GlobalNPC.SetDefaultsFromNetId(NPC npc) also runs after the mobile game's
negative-ID variant setup, when netID has its final value.
Use AIType to borrow a vanilla type's AI while keeping this NPC's own stats.
Set a matching NPC.aiStyle; NPCAIStyleID exposes the named style constants,
and NPCAIStyleID.Search maps those names and IDs in both directions.
The type substitution is limited to vanilla AI, and NPC.ModNPC keeps the
same managed instance during that call. NPC.VanillaAI() calls just vanilla
AI, whereas NPCLoader.NPCAI(npc) includes the lifecycle callbacks.
AnimationType independently borrows vanilla framing. Set
Main.npcFrameCount[Type] in SetStaticDefaults to match the intended sheet.
The borrowed routine uses the mod NPC's texture and frame count. FindFrame
then runs even if vanilla framing ran; it is not a replacement for vanilla
framing. Change NPC.frame.Y, NPC.frameCounter and NPC.spriteDirection
there to supply custom animation.
For hit effects, npc.HitEffect(hit) preserves the supplied HitInfo.
The overload HitEffect(int hitDirection = 0, double dmg = 10, bool? instantKill = null) reconstructs legacy metadata, treating damage
9999 as an instant kill unless explicitly overridden. Calls originating from
the game's two-argument method have legacy damage/direction metadata.
Item and projectile combat integrations supply their richer combat data in
the corresponding combat steps.
For damage over time, subtract from NPC.lifeRegen rather than replacing
other mods' contributions. Raise damage when a larger damage batch is
needed. Vanilla DOT can block positive regeneration after the hook; the
adapter preserves the requested damage batch through the mobile game's
DOTTally calculation. The callbacks also work for vanilla NPCs.
The scaling callback receives bossAdjustment == 1f, matching the selected
local tModLoader checkout. Its patch currently uses a placeholder value here;
the adapter does not substitute the older master-mode adjustment. The mobile
game's final player-count multiplier still runs after the callbacks.
The ExampleCustomAISlimeNPC port demonstrates the five-state Flutter Slime
AI and its six animation frames, and its own banner (EnemyBanner and
ExampleCustomAISlimeNPCBanner). Its natural spawning, platform
fall-through and collision-damage behavior are deferred to their planned
steps. Immunity to ExampleGravityDebuff, and PartyZombie's custom liquid
gravity adjustments, require the separate NPC gravity-multiplier API; those
parts are explicitly deferred. Existing vanilla sounds are used.
These hooks belong to the target. A GlobalNPC adds NPC npc as its first
parameter:
| Hook | Behavior |
|---|---|
CanBeHitByItem(Player player, Item item) |
Returns bool?: false blocks, true permits otherwise restricted targets such as friendly NPCs, and null keeps the default. NPC globals run first, followed by the mod NPC. A false stops the remaining NPC callbacks. |
CanCollideWithPlayerMeleeAttack(Player player, Item item, Rectangle meleeAttackHitbox) |
Returns bool? to replace the melee collision decision. It does not bypass the game's wall or invulnerability checks. NPC globals run before the mod NPC. |
ModifyIncomingHit(ref NPC.HitModifiers modifiers) |
The mod NPC runs before its globals, at the start of the accepted item strike, before item-specific modifiers. |
ModifyHitByItem(Player player, Item item, ref NPC.HitModifiers modifiers) |
The mod NPC runs before its globals, after the item callbacks and before the player's callbacks. |
OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone) |
The mod NPC runs before its globals, after the item callbacks and before the player's callbacks. Use this for side effects after the strike. |
Across player, item and NPC decision sources, the first non-null decision
has priority, following the selected local CombinedHooks. An earlier false
ends the checks; after a true, later sources still run and their decisions do
not replace it. Within the NPC source, any global or mod NPC false vetoes that
source. The player's general CanHitNPC veto runs before its nullable
CanHitNPCWithItem decision.
The damage order is incoming NPC modifiers, item modifiers, NPC item
modifiers, then player modifiers. The post-hit order is item, NPC, then
player. HitEffect receives the full item hit metadata, including its damage
class, source damage and critical flag. hit.Damage describes the strike;
damageDone is limited to available health and is zero for an immortal
target. An accepted hit still has a post-hit callback when the target is
immortal. A nested raw StrikeNPC is not attributed to the outer item.
The hooks extend the existing item combat path. They also install that path when only NPC callbacks are present and the weapon is vanilla. The adapter retains the mobile raw-damage message 28 flow and skips local modifiers on a strike received from the network. A two-device network result is still pending the coordinated network steps.
The final damage is exact, critical hits included. The game's own strike
can only produce critical damage of the defense's parity (even against even
defense) and at least 2, so a critical hit the modifiers bring to such a value
(SetMaxDamage(3) against defense 10, SetMaxDamage(1)) is struck as a normal
hit for that damage: the hit stays critical for every hook, the damage number
keeps the critical color and size, and the knockback gets the game's critical
1.4 multiplier (applied before the game's knockback taper, so very strong
knockback can differ slightly). Other players receive the same damage.
ModifyIncomingHit runs at the start of item strikes, of projectile strikes,
of NPC contact strikes and of direct calls to NPCLoader.ModifyIncomingHit.
Raw NPC.StrikeNPC calls by themselves do not enter these callbacks.
DamageModificationGlobalNPC and ExampleDefenseDebuff demonstrate a
temporary 25% defense reduction. The global resets its per-entity flag before
buff updates; the buff sets it again, and the incoming hook changes
modifiers.Defense. The debuff inherits Ichor immunity. The global's
DrawEffects tints the NPC (drawColor.G = 0), and the player branch uses
the mobile integer defense field. PartyZombie's incoming hook reduces magic damage by 75%; projectile
magic damage receives the same behavior.
| Hook | Behavior |
|---|---|
CanBeHitByProjectile(Projectile projectile) |
Returns bool?: false blocks the projectile, null keeps the default. NPC globals run first, followed by the mod NPC; a false stops the rest. |
ModifyHitByProjectile(Projectile projectile, ref NPC.HitModifiers modifiers) |
The mod NPC runs before its globals, after the projectile's own ModifyHitNPC and before the owner's ModPlayer hooks. |
OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone) |
Same order, after the projectile's OnHitNPC. |
The decision order is tModLoader's CombinedHooks.CanHitNPCWithProj: the
owner's ModPlayer, then the projectile and its globals, then the NPC; the
first non-null answer wins and a false before it stops the checks. The damage
order is ModifyIncomingHit, the projectile, the NPC, then the owner, and
damageDone is limited to the health left, as for items. These hooks run for
the game's projectiles too, and an NPC that overrides them installs the
projectile strike path by itself.
The server syncs an NPC with message 23 (position, velocity, ai, life).
Fields of your own travel with SendExtraAI(BinaryWriter writer) and
ReceiveExtraAI(BinaryReader reader). Set NPC.netUpdate = true when they
change, and read them back in the same order. A GlobalNPC has
SendExtraAI(npc, bitWriter, binaryWriter) and
ReceiveExtraAI(npc, bitReader, binaryReader). The layout and the
underflow errors are the same as for projectiles. The data goes from the
server to the clients only, with the game's message, and is applied once the
client has read it. NPCLoader.WriteExtraAI/ReceiveExtraAI are public.
Every mod NPC gets a bestiary entry: a town NPC entry for town NPCs, a critter
entry for NPCID.Sets.CountsAsCritter, an enemy entry otherwise. Its drops
come from ModifyNPCLoot. Add the rest in SetBestiary:
public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry)
{
bestiaryEntry.Info.AddRange([
BestiaryDatabaseNPCsPopulator.CommonTags.SpawnConditions.Biomes.Surface,
new FlavorTextBestiaryInfoElement("Mods.ExampleMod.Bestiary.ExamplePerson_1"),
]);
}GlobalNPC.SetBestiary(NPC npc, BestiaryDatabase database, BestiaryEntry bestiaryEntry)
runs for the game's NPCs too. bestiaryEntry.Info has Add, AddRange,
Count, the indexer, RemoveAt and RemoveAll. When a global changes the loot
of the game's NPCs, their entries list the new drops.
How the NPC looks in the bestiary is set in SetStaticDefaults, as in
tModLoader:
NPCID.Sets.NPCBestiaryDrawModifiers drawModifiers = new() { Velocity = 1f, Direction = 1 };
NPCID.Sets.NPCBestiaryDrawOffset.Add(Type, drawModifiers);
ContentSamples.NpcBestiaryRarityStars[Type] = 3;Hide = true leaves the NPC out of the bestiary, as for worm bodies and tails.
A CustomTexturePath from the mod ("ExampleMod/Content/NPCs/MyIcon") becomes
the entry's icon in place of the drawn NPC; the game's own Images/... paths
work as well. NPCBestiaryDrawOffset also has TryGetValue, Remove,
ContainsKey and the indexer: ExamplePerson turns slowly in the bestiary by
replacing its modifiers in PreDraw.
SpawnModBiomes lists the mod biomes the NPC belongs to, which
the bestiary shows in its entry, as in tModLoader.
| Hook | Behavior |
|---|---|
CanHitPlayer(Player target, ref int cooldownSlot) |
false stops the contact damage. NPC globals run first, then the mod NPC; a false stops the rest. Runs before the player's ModPlayer.CanBeHitByNPC. |
ModifyHitPlayer(Player target, ref Player.HurtModifiers modifiers) |
The mod NPC, then its globals, then the player's ModifyHitByNPC and ModifyHurt. |
OnHitPlayer(Player target, Player.HurtInfo hurtInfo) |
Same order, after the game applied the hit. |
CanHitNPC(NPC target) |
A hostile NPC touching a friendly one (a town NPC, for example). false stops it. |
CanBeHitByNPC(NPC attacker) |
The other side of the same check. |
ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) |
After the target's ModifyIncomingHit; the mod NPC, then its globals. |
OnHitNPC(NPC target, NPC.HitInfo hit) |
Same order, after the damage. |
The NPC × NPC check follows tModLoader's NPCLoader.CanHitNPC: the attacker's
globals, the target's globals (CanBeHitByNPC), the attacker, then the
target; the first false wins. The contact goes through the game's
NPC.BeHurtByOtherNPC, so a false there also skips the knockback and the
immunity frames. The player side uses the same Player.Hurt path as the
ModPlayer hooks, with the NPC's cooldownSlot passed on to them.
Use Terraria.GameContent.ItemDropRules for rules and Terraria.ModLoader
for NPCLoot, GlobalLoot and ItemLoot. Loot tables are built once after
content setup. A mod NPC runs before its applicable globals; ModifyGlobalLoot
runs once per global, after the per-NPC tables. AppliesToEntity(npc, false)
filters a global's per-type loot changes, including vanilla NPC variants.
public override void ModifyNPCLoot(NPCLoot npcLoot)
{
npcLoot.Add(ItemDropRule.Common(ModContent.ItemType<ExampleItem>(), 2, 1, 3));
var daytime = new LeadingConditionRule(new DayDropCondition());
daytime.OnSuccess(ItemDropRule.Common(ItemID.Wood));
npcLoot.Add(daytime);
}A GlobalNPC receives ModifyNPCLoot(NPC npc, NPCLoot npcLoot) and
ModifyGlobalLoot(GlobalLoot globalLoot). All three loot views implement
ILoot: Add, Remove, RemoveWhere and Get return or operate on
IItemDropRule objects. Get() includes global drops for NPC tables;
Get(false) returns only that NPC's own rules. Removing a rule from an NPC
does not remove a global rule. Use GlobalLoot to change global entries.
Get returns a new list containing the existing rules; modifying the list
does not modify the table. Remove expects a rule retrieved from the table.
npcLoot.RemoveWhere(rule => rule is CommonDrop drop && drop.itemId == ItemID.Gel, false);
foreach (IItemDropRule rule in npcLoot.Get(false))
if (rule is CommonDrop drop && drop.itemId == ItemID.Wood)
drop.chanceDenominator = 3;The database, factory rules, chance rolls, player luck and chain resolution
use the mobile game's objects. Factories include Common, NotScalingWithLuck,
ScalingWithOnlyBadLuck, WithRerolls, BossBag, ByCondition,
OneFromOptions, NormalvsExpert, MasterModeCommonDrop and the game's
other factory variants. CommonDrop exposes its native item, chance and
stack fields. Existing DropBasedOnExpertMode rules expose their child
rules. Option arrays are copied across the interop boundary; assign the
edited array back to dropIds or options.
Custom conditions implement IItemDropRuleCondition:
public sealed class DayDropCondition : IItemDropRuleCondition
{
public bool CanDrop(DropAttemptInfo info) => Main.dayTime;
public bool CanShowItemDropInUI() => true;
public string GetConditionDescription() => "During daytime";
}Conditions.* wraps the conditions present in the mobile game, including
IsExpert, NotExpert, IsMasterMode, NotMasterMode, IsHardmode and
NamedNPC. OnSuccess, OnFailedRoll and OnFailedConditions add native
chains and return the child rule. The editable ChainedRules list is
synchronized when a rule is registered, resolved or reported. Adapters whose
managed chain lists are exposed remain alive for the content lifetime so
list edits survive garbage collection. A custom
IItemDropRule implements CanDrop, TryDroppingItem, ReportDroprates
and the chain list; INestedItemDropRule also receives a resolver callback.
CommonCode.DropItem(info, itemType, stack) supports both NPC and item
attempts. Use info.rng for rolls. ItemDropAttemptResult.State selects
Success, FailedRandomRoll, DoesntFillConditions or DidNotRunCode.
ReportDroprates accepts a managed List<DropRateInfo> and
DropRateInfoChainFeed. Reports from native rules and custom rules preserve
stacks, probabilities and condition objects. The current step does not
refresh already built bestiary entries or add bestiary UI hooks; that work
remains in the bestiary step.
| Death hook | Behavior |
|---|---|
PreKill() |
All applicable globals run first and their results are combined. If all allow the death, the mod NPC runs. A false skips the loot and death-event tail, including OnKill. |
OnKill() |
The mod NPC, then its globals, after item drops and before the game's death events. |
BossLoot(ref int potionType, ref int potionStack, ref int heartStack) |
Changes the boss potion and heart drops. Zero stacks suppress the corresponding drops. |
The current local tModLoader uses the three-parameter BossLoot signature.
The one-parameter BossLoot(ref int potionType) remains available as a
compatibility bridge; the base three-parameter method calls it. There is
no CanDropLoot virtual in the selected checkout, so none is introduced.
The native stages preserve the game's authority, statue and special-world
filters before PreKill. These are death-only hooks, with no new AI,
drawing or per-frame NPC callback. Multiplayer validation remains part of
the coordinated two-device network windows.
For a right-click container, override ModItem.ModifyItemLoot(ItemLoot itemLoot)
or GlobalItem.ModifyItemLoot(Item item, ItemLoot itemLoot). A mod container
also needs CanRightClick() to allow opening. The game still controls the
open action and item consumption; ConsumeItem can keep the container.
public override bool CanRightClick() => true;
public override void ModifyItemLoot(ItemLoot itemLoot)
{
itemLoot.Add(ItemDropRule.Common(ModContent.ItemType<ExampleItem>(), 1, 2, 4));
}During an item attempt, info.item is the container type, info.npc is
null and info.player is the opener. Native rules use a scoped NPC adapter
at the player's bounds, and their drops use the player's open-item source.
Boss bags set the attempt's expert flag. Direct calls to
ItemDropResolver.TryDropping, ResolveRule and a native rule's
TryDroppingItem accept the same managed item attempt context.
The mobile database has no item
table: ItemLoot stores registered rules in a managed table and resolves
them through the native resolver. Vanilla containers retain their game's
hardcoded contents; Get and removal expose registered rules only. They do
not extract or remove those hardcoded vanilla contents.
The Example Mod covers the common cases. Its PartyZombie copies the Zombie's
loot and adds Confetti. ExampleNPCLoot, a GlobalNPC, gives ExampleItem
to every enemy that is not a critter, replaces the Guide's cap rule, makes the
Dreadnautilus drop its Sanguine Staff more often in normal mode, adds the
WaspNest to the Queen Bee's choice of weapons, drops the other evil's chunk
from Crimeras and Corruptors under a condition of its own, gives slimes a rare
ExampleSword during the day, and puts ExampleSoul in the global loot
(ModifyGlobalLoot), which any enemy drops when the soul's condition is met. The Minion Boss shows a boss's loot: a
trophy, a mask and a stack of items outside Expert Mode, its treasure bag in
Expert Mode (ItemDropRule.BossBag), and a relic and a pet in Master Mode.
Natural spawning uses the mobile game's NPC.Spawner. Override
ModNPC.SpawnChance(NPC.Spawner spawner) to contribute a positive weight:
using Terraria;
using Terraria.ModLoader;
using Terraria.ModLoader.Utilities;
public override float SpawnChance(NPC.Spawner spawner) =>
SpawnCondition.OverworldNightMonster.Chance * 0.2f;The conditions and their Chance values follow the local tModLoader's
SpawnCondition tree. They are evaluated for the current attempt before mod
weights are collected. Use them on the game thread, inside the spawn
callbacks. The native spawner retains its invasion, water, biome, safety and
special-world flags. SpawnTileX, SpawnTileY, GroundTileY,
SpawnTileType, SpawnWallType, Player and SafeRangeX expose the selected
attempt through the same spawner.
GlobalNPC.EditSpawnRate edits the rate and maximum count for a player.
EditSpawnRange edits the horizontal/vertical spawn and safe ranges, in
tiles. A rate is clamped to at least one; a maximum count of zero disables
natural spawning. EditSpawnFlags runs after the native player flags;
EditSpawnInfo runs after the chosen tile's flags. Both receive the live
NPC.Spawner. NPCID.Sets remains backed by the game's resized native arrays.
public override void EditSpawnPool(IDictionary<int, float> pool, NPC.Spawner spawner)
{
if (spawner.Player.ZoneDungeon) pool[ModContent.NPCType<MyNPC>()] = 0.5f;
}Pool key 0 has weight 1 initially and selects the original mobile spawn
branch. Removing it gives mods control over the whole attempt. An empty pool
spawns nothing. Positive registered types and vanilla negative net IDs are
accepted; invalid IDs, non-positive weights, NaN and infinity are ignored.
ModNPC.SpawnNPC(int tileX, int tileY) can replace creation. The default
creates an NPC at the selected tile with the natural-spawn entity source.
Applicable GlobalNPC.SpawnNPC(int npc, int tileX, int tileY) callbacks run
with the resulting NPC index after creation. Selection and notification run
on the server or in a standalone world.
The older SpawnChance(NPCSpawnInfo) and
EditSpawnPool(IDictionary<int, float>, NPCSpawnInfo) signatures also work.
Their snapshot includes the selected tile, player and the standard biome
flags. Prefer the live spawner contract when porting the local tModLoader.
The mobile 1.4.5 flags do not preserve every old 1.4.4 distinction:
PlayerSafe is mapped from spawnFriendly || noWorms, and
PlayerInTown from spawnFriendly.
PartyZombie and ExampleCustomAISlimeNPC show the two common cases: a monster of the night and a slime of the day.
Set immunity by NPC type in SetStaticDefaults:
public override void SetStaticDefaults()
{
NPCID.Sets.SpecificDebuffImmunity[Type][BuffID.Poisoned] = true;
NPCID.Sets.ImmuneToRegularBuffs[Type] = true;
NPCID.Sets.SpecificDebuffImmunity[Type][BuffID.OnFire] = false;
}NPCID.Sets.ImmuneToRegularBuffs excludes tag buffs, while
ImmuneToWhipTags covers tag buffs. The masks combine when both are true.
SpecificDebuffImmunity is indexed by NPC type and buff type: null keeps the
default, true forces immunity, and false forces vulnerability. The tables
include registered mod NPCs and buffs and preserve the mobile game's
declared vanilla immunities.
These managed sets initialize on first use and enable NPC defaults support
even for a mod that does not add a ModNPC or GlobalNPC. Reading unrelated
game NPCID.Sets members does not enable that support. Instance cloning
hooks are installed only when NPC or global NPC content is registered.
BuffID.Sets.IsATagBuff marks tag buffs. Add parent buff types to
BuffID.Sets.GrantImmunityWith[Type] in a mod buff's SetStaticDefaults to
inherit their NPC immunity. For an ordinarily vulnerable NPC, any immune
parent grants immunity. For a broadly immune NPC, vulnerability to every
parent grants vulnerability. Explicit overrides have final priority.
npc.BecomeImmuneTo(buffType) changes a live NPC and also grants immunity to
buffs that directly inherit from that buff. Follow it with
npc.ClearImmuneToBuffs(out bool anyBuffsCleared) to remove active buffs to
which the NPC is now immune. Run this change on the authoritative side; the
clear helper sends message 54 for mobile server/host modes. Network validation
is part of the coordinated multiplayer steps.
These ModNPC and GlobalNPC hooks follow tModLoader's names, parameters
and order. Each one installs its game hook the first time a loaded type
overrides it; a mod that doesn't override any of them adds no cost.
| Hook | When it runs |
|---|---|
CanFallThroughPlatforms |
The NPC decides whether to fall through platforms. false wins over true; null keeps the game's choice. |
ModifyCollisionData |
Before contact damage: change the immunity slot (ImmunityCooldownID), the damage multiplier and the hitbox. false skips the game's special hitboxes. |
SpecialOnKill |
At the start of the loot; true skips the drops (also the Eater of Worlds' segment loot). |
DeathMessage / ModifyDeathMessage
|
The red town NPC death message and the purple boss defeat message, in singleplayer and on the server. false hides the message. |
ModifyTypeName |
Every npc.TypeName read. |
CanGoToStatue / OnGoToStatue
|
When the king or queen statue is activated by wire. A mod NPC must return true; a global can let a vanilla NPC in or keep it out. |
CanBeCaughtBy / OnCaughtBy
|
Bug net swings. true catches even without catchItem rules; failed is true when lava bait hurts the player. |
UsesPartyHat |
Whether a town NPC wears the party hat. |
BuffTownNPC (global) |
After each town NPC update: extra defense, and a damage multiplier applied to town NPC attacks. |
DrawHealthBar |
For each health bar under an NPC. false hides it, true draws it at the changed position and scale. |
PartyHatPosition / ChatBubblePosition
|
Changes where the hat (world coordinates) and the chat bubble (screen coordinates) are drawn, and their flip. |
ModifyHoverBoundingBox / PreHoverInteract
|
The box the mouse hovers to talk to the NPC or see its name; PreHoverInteract returning false ignores the NPC this frame. |
NeedSaving / SaveData / LoadData
|
The world save. See below. |
TownNPCProfile / ModifyTownNPCProfile (global) |
The town NPC's appearance profile. See below. |
Happiness goes in SetStaticDefaults through NPC.Happiness.
ModifyNPCHappiness also runs here, when the game works out the shop price,
with primaryPlayerBiome always 0.
In tModLoader the hook exists but its call is commented out.
World save. A mod NPC is saved when it is a town NPC, when
NPCID.Sets.SavesAndLoads is set, or when NeedSaving() returns true.
A global's NeedSaving(npc) also keeps vanilla NPCs that the game wouldn't
save. Data from SaveData goes into <world>.wld.npcs.bl, next to the world,
never into the .wld. On load, LoadData gets the same TagCompound back
after SetDefaults. A global's data is stored under its mod and name, and
also works for vanilla town NPCs that the .wld saves. Data from a mod that
isn't loaded is dropped on the next save.
public class Totem : ModNPC
{
public int Charges;
public override bool NeedSaving() => true;
public override void SaveData(TagCompound tag) => tag["charges"] = Charges;
public override void LoadData(TagCompound tag) => Charges = tag.GetInt("charges");
}Town NPC profiles. TownNPCProfile() returns an ITownNPCProfile. It
picks the variation and name when the NPC appears, the texture for each
frame and the head index. Profiles.DefaultNPCProfile(texture, headIndex, partyTexture) and Profiles.StackedNPCProfile(...) work as in tModLoader:
the second profile is the shimmer one. Mod.AddNPCHeadTexture(Type, path)
in Load registers the shimmer head. Unlike tModLoader, its slot is only
known from SetStaticDefaults on, through NPCHeadLoader.GetHeadSlot(path):
static Profiles.StackedNPCProfile profile = null!;
public override void Load() => Mod.AddNPCHeadTexture(Type, Texture + "_Shimmer_Head");
public override void SetStaticDefaults()
{
profile = new Profiles.StackedNPCProfile(
new Profiles.DefaultNPCProfile(Texture, NPCHeadLoader.GetHeadSlot(HeadTexture), Texture + "_Party"),
new Profiles.DefaultNPCProfile(Texture + "_Shimmer", NPCHeadLoader.GetHeadSlot(Texture + "_Shimmer_Head"), Texture + "_Shimmer_Party"));
}
public override ITownNPCProfile TownNPCProfile() => profile;A global's ModifyTownNPCProfile(npc) overrides the profile of any town NPC,
vanilla or modded; null keeps the current one. The game keeps calling its
own profiles directly; only types with a C# profile go through C#.
ExamplePerson uses this to switch its party and shimmer textures.
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.
