Skip to content

API NPCs

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

API reference · generated by tools/docs/ApiReference, do not edit by hand

NPCs, town NPCs, shops, bestiary, profiles, loot and invasions.

AbstractNPCShop

abstract class Terraria.ModLoader.AbstractNPCShop

A shop of any shape. Most mods use NPCShop.

Member Kind tModLoader What it does
int NpcType property same The NPC that owns the shop.
string Name property same The shop's own name, such as Shop.
string FullName property same The shop's name in NPCShopDatabase.
IEnumerable<Entry> AllEntries hook same Every line of the shop.
IEnumerable<Entry> ActiveEntries property same The lines whose conditions hold now.
new AbstractNPCShop(int npcType, string name) constructor same Creates an instance.
void Register() method same Called by the loader to register this content. Mods do not call it.
void FillShop(ICollection<Item> items, NPC npc) hook same Unbounded variant of FillShop, for future forwards compatibility with tabbed or scrolling shops.
void FillShop(Item[] items, NPC npc, out bool overflow) hook same Fills a shop array with the contents of this shop, evaluating conditions and running callbacks.
void FinishSetup() hook same Called once after all mods have added their lines.
void RefreshItems(bool onlyIfVariantChanged) hook same Fills the shop again.

AbstractNPCShop.Entry

class Terraria.ModLoader.AbstractNPCShop.Entry

One line of a shop: the item and its conditions.

Member Kind tModLoader What it does
Item Item property same The item sold.
IEnumerable<Condition> Conditions property same What must hold to sell it.
bool Disabled property same Whether the line is off.
new Entry(Item item, params Condition[] conditions) constructor only here Creates an instance.
void Disable() method same Turns the line off.
void AddCondition(Condition condition) method same Adds a condition.
bool ConditionsMet() method same Whether all conditions hold.

AutoloadBossHead

class Terraria.ModLoader.AutoloadBossHead : Attribute

This attribute annotates a ModNPC class to indicate that the game should autoload the boss head texture found at BossHeadTexture.

Member Kind tModLoader What it does

AutoloadHead

class Terraria.ModLoader.AutoloadHead : Attribute

This attribute annotates a ModNPC class to indicate that the game should autoload the head texture found at HeadTexture.

Member Kind tModLoader What it does

BestiaryEntry

struct Terraria.GameContent.Bestiary.BestiaryEntry

An NPC's page in the bestiary. Info holds what the page shows.

Member Kind tModLoader What it does
BestiaryInfoList Info property differs What the page shows. Add yours in SetBestiary. tML: List<IBestiaryInfoElement> Info

BestiaryInfoList

struct Terraria.GameContent.Bestiary.BestiaryInfoList : IEnumerable<IBestiaryInfoElement> · only in Bunny Loader

The list behind BestiaryEntry.Info, with Add and AddRange.

Member Kind tModLoader What it does
int Count property only here How many items it holds.
IBestiaryInfoElement this[int index] indexer only here Reads or writes one entry.
void Add(IBestiaryInfoElement element) method only here Adds an element.
void AddRange(IEnumerable<IBestiaryInfoElement> elements) method only here Adds several elements.
void RemoveAt(int index) method only here Removes one by position.
int RemoveAll(Predicate<IBestiaryInfoElement> match) method only here Removes those that match.
IEnumerator<IBestiaryInfoElement> GetEnumerator() method only here Walks the items in foreach.

BossBarDrawParams

struct Terraria.DataStructures.BossBarDrawParams

Holds data required for boss bar drawing.

Member Kind tModLoader What it does
Texture2D BarTexture field same The texture with fixed dimensions (516x348) containing all the necessary parts.
Vector2 BarCenter field same The screen position of the center of the bar.
Color BarColor field same The tint of the Bar.
Texture2D IconTexture field same The displayed icon texture.
Rectangle IconFrame field same The icon textures frame.
Color IconColor field same The tint of the icon.
float Life field same The current life of the boss
float LifeMax field same The max life of the boss (the amount it spawned with)
float Shield field same The current shield of the boss
float ShieldMax field same The max shield of the boss (may be 0 if the boss has no shield)
float IconScale field same The scale the icon is drawn with. Defaults to 1f, modify if icon is bigger or smaller than 26x28.
bool ShowText field same If the current life (or shield) of the boss should be written on the bar.
Vector2 TextOffset field same The text offset from the center (BarCenter)
new BossBarDrawParams(Texture2D barTexture, Vector2 barCenter, Texture2D iconTexture, Rectangle iconFrame, Color iconColor, float life, float lifeMax, Color barColor, float shield, float shieldMax, float iconScale, bool showText, Vector2 textOffset) constructor same Creates an instance.
void Deconstruct(out Texture2D barTexture, out Vector2 barCenter, out Color barColor, out Texture2D iconTexture, out Rectangle iconFrame, out Color iconColor, out float life, out float lifeMax, out float shield, out float shieldMax, out float iconScale, out bool showText, out Vector2 textOffset) method same Takes the value apart in a var (a, b) = value assignment.

BossBarLoader

static class Terraria.ModLoader.BossBarLoader

Runs the hooks of mod boss bars.

Member Kind tModLoader What it does
ModBossBarStyle CurrentStyle static property same The bar style in use.
void SwitchBossBarStyle(ModBossBarStyle bossBarStyle) static method only here Changes the bar style.
int BossBarCount static property only here How many exist, with the game's and every mod's.
ModBossBar GetBossBar(int type) static method only here The ModBossBar of a number, or null.
bool NpcToBossBar(NPC npc, out ModBossBar value) static method same Gets the ModBossBar associated with this NPC
bool PreDraw(SpriteBatch spriteBatch, NPC npc, ModBossBar bossBar, ref BossBarDrawParams drawParams) static method differs Allows you to draw things before the default draw code is ran. Return false to prevent drawing the ModBossBar. Returns true by default. tML: bool PreDraw(SpriteBatch spriteBatch, BigProgressBarInfo info, ref BossBarDrawParams drawParams)
void PostDraw(SpriteBatch spriteBatch, NPC npc, ModBossBar bossBar, BossBarDrawParams drawParams) static method differs Allows you to draw things after the bar has been drawn. skipped is true if you or another mod has skipped drawing the bar in PreDraw (possibly hiding it or in favor of new visuals). tML: void PostDraw(SpriteBatch spriteBatch, BigProgressBarInfo info, BossBarDrawParams drawParams)
Asset<Texture2D> VanillaBossBarTexture static property not here Not implemented.
Asset<Texture2D> GetTexture(ModBossBar bossBar) static method not here Returns the texture that the given bar is using. If it does not have a custom one, it returns the vanilla texture
void DrawFancyBar_TML(SpriteBatch spriteBatch, BossBarDrawParams drawParams) static method not here Draws a healthbar with fixed barTexture dimensions (516x348) where the effective bar top left starts at 32x24, and is 456x22 big The icon top left starts at 4x20, and is 26x28 big Frame 0 contains the frame (outline) Frame 1 contains the 2 pixel wide strip for the tip of the bar itself Frame 2 contains the 2 pixel wide strip for the bar itself, stretches out Frame 3 contains the background Frame 4 contains the 2 pixel wide strip for the tip of the bar itself (optional shield) Frame 5 contains the 2 pixel wide strip for the bar itself, stretches out (optional shield) Supply your own textures if you need a different shape/color, otherwise you can make your own method to draw it

EmoteBubble

struct Terraria.GameContent.UI.EmoteBubble

The emote bubble above a player or NPC. MakePlayerEmote shows one.

Member Kind tModLoader What it does
ModEmoteBubble ModEmoteBubble property same Its ModEmoteBubble, or null.
void MakePlayerEmote(Player player, int emoteId, bool syncBetweenClients) static method same Send a emote from the player
RefReadOnlyArray<GlobalEmoteBubble> EntityGlobals property not here Not implemented.
int WhoAmI property not here The whoAmI indicator that indicates this EmoteBubble, can be used in GetExistingEmoteBubble
bool IsFullyDisplayed property not here Whether or not this emote is fully displayed The first and the last 6 frames are for bubble-popping animation. The emote content is displayed after the animation
EmoteBubble GetExistingEmoteBubble(int whoAmI) static method not here Gets the emote bubble that exists in the world by WhoAmI. Returns null if there is no corresponding emote

EmoteBubbleLoader

static class Terraria.ModLoader.EmoteBubbleLoader

Registers emotes and runs their hooks.

Member Kind tModLoader What it does
int EmoteBubbleCount static property same How many exist, with the game's and every mod's.
ModEmoteBubble GetEmoteBubble(int type) static method same Gets the ModEmoteBubble instance corresponding to the specified ID.
void OnSpawn(EmoteBubble emoteBubble) static method same Gets called when your emote bubble spawns in world.
bool UpdateFrame(EmoteBubble emoteBubble) static method same Allows you to modify the frame of this emote bubble. Return false to stop vanilla frame update code from running. Returns true by default.
bool PreDraw(EmoteBubble emoteBubble, SpriteBatch spriteBatch, Texture2D texture, Vector2 position, Rectangle frame, Vector2 origin, SpriteEffects spriteEffects) static method same Allows you to draw things behind this emote bubble, or to modify the way this emote bubble is drawn. Return false to stop the game from drawing the emote bubble (useful if you're manually drawing the emote bubble). Returns true by default.
void PostDraw(EmoteBubble emoteBubble, SpriteBatch spriteBatch, Texture2D texture, Vector2 position, Rectangle frame, Vector2 origin, SpriteEffects spriteEffects) static method same Allows you to draw things in front of this emote bubble. This method is called even if PreDraw returns false.
Rectangle GetFrame(EmoteBubble emoteBubble) static method same Allows you to modify the frame rectangle for drawing this emote. Useful for emote bubbles that share the same texture.
Rectangle GetFrameInEmoteMenu(int emoteType, int frame, int frameCounter) static method same Allows you to modify the frame rectangle for drawing this emote in emotes menu. Useful for emote bubbles that share the same texture.
bool PreDrawInEmoteMenu(int emoteType, SpriteBatch spriteBatch, EmoteButton uiEmoteButton, Vector2 position, Rectangle frame, Vector2 origin) static method not here Not implemented.
void PostDrawInEmoteMenu(int emoteType, SpriteBatch spriteBatch, EmoteButton uiEmoteButton, Vector2 position, Rectangle frame, Vector2 origin) static method not here Not implemented.

tModLoader's EmoteBubbleLoader also has 1 public methods that only run the hooks of the same name. Here those runners are internal. Override the hook in your class instead.

EmoteID

static class Terraria.GameContent.UI.EmoteID

Emote types, and the categories of the emote menu in EmoteID.Category.

Member Kind tModLoader What it does
int EmotionLove const same
int EmotionAnger const same
int EmotionCry const same
int EmotionAlert const same
int Count const same How many items it holds.

EmoteID.Category

static class Terraria.GameContent.UI.EmoteID.Category

This class is added by TML for easily adding mod emotes to a specific category.

Member Kind tModLoader What it does
int General const same General Emotes
int RockPaperScissors const only here
int Items const same Items Emotes
int BiomesAndEvents const only here
int Town const same Town Emotes
int Critters const only here
int Bosses const only here
int Rps const not here Rock, Paper, Scissors! Emotes
int NatureAndWeather const not here Nature & Weather Emotes
int CrittersAndMonsters const not here Critters & Monsters Emotes
int Dangers const not here Dangers Emotes (For bosses)

GlobalBossBar

abstract class Terraria.ModLoader.GlobalBossBar : ModType

A class that is used to modify existing boss health bars. To add them, use ModBossBar instead.

Member Kind tModLoader What it does
bool PreDraw(SpriteBatch spriteBatch, NPC npc, ref BossBarDrawParams drawParams) hook same Allows you to draw things before the default draw code is ran. Return false to prevent drawing the bar. Returns true by default.
void PostDraw(SpriteBatch spriteBatch, NPC npc, BossBarDrawParams drawParams) hook same Allows you to draw things after the bar has been drawn. skipped is true if you or another mod has skipped drawing the bar (possibly hiding it or in favor of new visuals).

GlobalEmoteBubble

abstract class Terraria.ModLoader.GlobalEmoteBubble : GlobalType<EmoteBubble, GlobalEmoteBubble>

Changes emote bubbles of the game and of every mod.

Member Kind tModLoader What it does
void OnSpawn(EmoteBubble emoteBubble) hook same Gets called when emote bubbles spawn in world.
bool UpdateFrame(EmoteBubble emoteBubble) hook same Allows you to modify the frame of this emote bubble. Return false to stop vanilla frame update code from running. Returns true by default.
bool UpdateFrameInEmoteMenu(int emoteType, ref int frameCounter) hook same Allows you to modify the frame of this emote bubble which displays in emotes menu. Return false to stop vanilla frame update code from running. Returns true by default. Do note that
bool PreDraw(EmoteBubble emoteBubble, SpriteBatch spriteBatch, Texture2D texture, Vector2 position, Rectangle frame, Vector2 origin, SpriteEffects spriteEffects) hook same Allows you to draw things behind this emote bubble, or to modify the way this emote bubble is drawn. Return false to stop the game from drawing the emote bubble (useful if you're manually drawing the emote bubble). Returns true by default.
void PostDraw(EmoteBubble emoteBubble, SpriteBatch spriteBatch, Texture2D texture, Vector2 position, Rectangle frame, Vector2 origin, SpriteEffects spriteEffects) hook same Allows you to draw things in front of this emote bubble. This method is called even if PreDraw returns false.
Rectangle GetFrame(EmoteBubble emoteBubble) hook same Allows you to modify the frame rectangle for drawing this emote. Useful for emote bubbles that share the same texture.
Rectangle GetFrameInEmoteMenu(int emoteType, int frame, int frameCounter) hook same Allows you to modify the frame rectangle for drawing this emote in emotes menu. Useful for emote bubbles that share the same texture.
bool PreDrawInEmoteMenu(int emoteType, SpriteBatch spriteBatch, EmoteButton uiEmoteButton, Vector2 position, Rectangle frame, Vector2 origin) hook not here Allows you to draw things behind this emote bubble that displays in emotes menu, or to modify the way this emote bubble is drawn. Return false to stop the game from drawing the emote bubble (useful if you're manually drawing the emote bubble). Returns true by default.
void PostDrawInEmoteMenu(int emoteType, SpriteBatch spriteBatch, EmoteButton uiEmoteButton, Vector2 position, Rectangle frame, Vector2 origin) hook not here Allows you to draw things in front of this emote bubble. This method is called even if PreDraw returns false.

GlobalNPC

abstract class Terraria.ModLoader.GlobalNPC : GlobalType<NPC, GlobalNPC>

This class allows you to modify and use hooks for all NPCs, both vanilla and modded. To use it, simply create a new class deriving from this one. Implementations will be registered automatically.

Member Kind tModLoader What it does
void SetDefaults(NPC entity) hook only here Allows you to set all your NPC's properties, such as width, damage, aiStyle, lifeMax, etc.
void SetDefaultsFromNetId(NPC npc) hook same Called after SetDefaults for NPCs with a negative netID This hook is required because SetDefaultsFromNetId only sets netID after SetDefaults Remember that type does not support negative numbers and AppliesToEntity cannot distinguish between NPCs with the same type but different netID
void OnSpawn(NPC npc, IEntitySource source) hook same Gets called when any NPC spawns in world Called in single player or on the server only.
void ApplyDifficultyAndPlayerScaling(NPC npc, int numPlayers, float balance, float bossAdjustment) hook same Allows you to customize this NPC's stats when the difficulty is expert or higher. This runs after value, lifeMax, damage, knockBackResist have been adjusted for the current difficulty, (expert/master/FTW) It is common to multiply lifeMax by the balance factor, and sometimes adjust knockbackResist. Eg: lifeMax = (int)(lifeMax * balance * bossAdjustment)
void SendExtraAI(NPC npc, BitWriter bitWriter, BinaryWriter binaryWriter) hook same Use this judiciously to avoid straining the network. Checks and methods such as AppliesToEntity can reduce how much data must be sent for how many projectiles. Called whenever SyncNPC is successfully sent, for example on NPC creation, on player join, or whenever NPC.netUpdate is set to true in the update loop for that tick. Can be called on the server.
void ReceiveExtraAI(NPC npc, BitReader bitReader, BinaryReader binaryReader) hook same Use this to receive information that was sent in SendExtraAI. Called whenever SyncNPC is successfully received. Can be called on multiplayer clients.
void BossHeadSlot(NPC npc, ref int index) hook same Allows you to customize the boss head texture used by an NPC based on its state. Set index to -1 to stop the texture from being displayed. Called on all clients.
void BossHeadRotation(NPC npc, ref float rotation) hook same Allows you to customize the rotation of an NPC's boss head icon on the map. Called on all clients.
void BossHeadSpriteEffects(NPC npc, ref SpriteEffects spriteEffects) hook same Allows you to flip an NPC's boss head icon on the map. Called on all clients.
Color GetAlpha(NPC npc, Color drawColor) hook same Allows you to determine the color and transparency in which an NPC is drawn. Return null to use the default color (normally light and buff color). Returns null by default. Called on all clients.
void DrawEffects(NPC npc, ref Color drawColor) hook same Allows you to add special visual effects to an NPC (such as creating dust), and modify the color in which the NPC is drawn. Called on all clients.
bool PreDraw(NPC npc, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) hook same Allows you to draw things behind an NPC, or to modify the way the NPC is drawn. Substract screenPos from the draw position before drawing. Return false to stop the game from drawing the NPC (useful if you're manually drawing the NPC). Returns true by default. Called on all clients.
void PostDraw(NPC npc, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) hook same Allows you to draw things in front of this NPC. Substract screenPos from the draw position before drawing. This method is called even if PreDraw returns false. Called on all clients.
void DrawBehind(NPC npc, int index) hook same When used in conjunction with "npc.hide = true", allows you to specify that this npc should be drawn behind certain elements. Add the index to one of Main.DrawCacheNPCsMoonMoon, DrawCacheNPCsOverPlayers, DrawCacheNPCProjectiles, or DrawCacheNPCsBehindNonSolidTiles. Called on all clients.
void SetBestiary(NPC npc, BestiaryDatabase database, BestiaryEntry bestiaryEntry) hook same Allows you to set an NPC's information in the Bestiary.
int PickEmote(NPC npc, Player closestPlayer, List<int> emoteList, WorldUIAnchor otherAnchor) hook same Allows you to change the emote that the NPC will pick Called in single player or on the server only. Phone: otherAnchor can be null: check otherAnchor.IsNull before reading it.
void EmoteBubblePosition(NPC npc, ref Vector2 position, ref SpriteEffects spriteEffects) hook same Allows you to change the location and sprite direction of the emote bubble when anchored to an NPC. Called on all clients.
bool CanFallThroughPlatforms(NPC npc) hook same Allows you to determine how and when an NPC can fall through platforms and similar tiles. Return true to allow an NPC to fall through platforms, false to prevent it. Returns null by default, applying vanilla behaviors (based on aiStyle and type). Called on the server and clients.
bool ModifyCollisionData(NPC npc, Rectangle victimHitbox, ref int immunityCooldownSlot, ref MultipliableFloat damageMultiplier, ref Rectangle npcHitbox) hook same Allows you to modify the NPC's , damage multiplier, and hitbox. Useful for implementing dynamic damage hitboxes that change in dimensions or deal extra damage. Returns false to prevent vanilla code from running. Returns true by default. Called on the server and clients.
bool SpecialOnKill(NPC npc) hook same Allows you to call OnKill on your own when the NPC dies, rather then letting vanilla call it on its own. Returns false by default. Called on the server and clients.
bool ModifyDeathMessage(NPC npc, ref NetworkText customText, ref Color color) hook same Allows you to modify the death message of a town NPC or boss. This also affects what the dropped tombstone will say in the case of a town NPC. The text color can also be modified. When modifying the death message, use GetFullNetName to retrieve the NPC name to use in substitutions. Return false to skip the vanilla code for sending the message. This is useful if the death message is handled by this method or if the message should be skipped for any other reason, such as if there are multiple bosses. Returns true by default.
void ModifyTypeName(NPC npc, ref string typeName) hook same Allows you to modify the type name of this NPC dynamically.
bool CanGoToStatue(NPC npc, bool toKingStatue) hook same Whether this NPC can be teleported to a King or Queen statue. Return true to allow the NPC to teleport to the statue, return false to block this NPC from teleporting to the statue, and return null to use the vanilla code for whether the NPC can teleport to the statue. Returns null by default. Called in single player or on the server only.
void OnGoToStatue(NPC npc, bool toKingStatue) hook same Allows you to make things happen when this NPC teleports to a King or Queen statue. Called in single player or on the server only.
bool CanBeCaughtBy(NPC npc, Item item, Player player) hook same Allows you to determine whether the given item can catch the given NPC. Return true or false to say the given NPC can or cannot be caught, respectively, regardless of vanilla rules. Returns null by default, which allows vanilla's NPC catching rules to decide the target's fate. If this returns false, OnCatchNPC is never called. NOTE: this does not classify the given item as an NPC-catching tool, which is necessary for catching NPCs in the first place. To do that, you will need to use the "CatchingTool" set in ItemID.Sets. Called on the local client only.
void OnCaughtBy(NPC npc, Player player, Item item, bool failed) hook same Allows you to make things happen when the given item attempts to catch the given NPC. Called on the local client only.
void BuffTownNPC(ref float damageMult, ref int defense) hook differs Allows you to modify the stats of town NPCs. Useful for buffing town NPCs when certain bosses are defeated, etc. Called on the server and clients. tML: void BuffTownNPC(NPC npc, ref float damageMult, ref float attackSpeedMult, ref int defense, ref int maxLife)
bool DrawHealthBar(NPC npc, byte hbPosition, ref float scale, ref Vector2 position) hook same Allows you to control how the health bar for the given NPC is drawn. The hbPosition parameter is the same as Main.hbPosition; it determines whether the health bar gets drawn above or below the NPC by default. The scale parameter is the health bar's size. By default, it will be the normal 1f; most bosses set this to 1.5f. Return null to let the normal vanilla health-bar-drawing code to run. Return false to stop the health bar from being drawn. Return true to draw the health bar in the position specified by the position parameter (note that this is the world position, not screen position). Called on all clients.
void PartyHatPosition(NPC npc, ref Vector2 position, ref SpriteEffects spriteEffects) hook same Allows you to fully control the location of the party and sprite direction of the party while an NPC is wearing it. can be used instead of this hook for a constant Y offset. can be additionally be used for the Y offset for the Town NPC's animations. Called on all clients.
void ChatBubblePosition(NPC npc, ref Vector2 position, ref SpriteEffects spriteEffects) hook same Allows you to change the location and sprite direction of the chat bubble that shows up while hovering over a Town NPC. Called on all clients.
void ModifyHoverBoundingBox(NPC npc, ref Rectangle boundingBox) hook same Allows you to modify the bounding box for hovering over the given NPC (affects things like whether or not its name is displayed). This hook won't be called if ShowNameOnHover is set to false. Called on the local client only.
bool PreHoverInteract(NPC npc, bool mouseIntersects) hook same Called when the NPC is selected via smart interact, or when the mouse is hovering over it. Right after ModifyHoverBoundingBox. Can be used to implement custom interact or hover behavior logic. By returning false, the vanilla code for town NPC chatting, drawing the chat bubble, and drawing the NPC name and life on the mouse is skipped. For example, the Old Shaking Chest NPC uses this to take a GoldenKey from the player and transform into Elder Slime. CanChat can be used to force smart interact to target this NPC as well, if desired. This hook won't be called if ShowNameOnHover is set to false. Called on the local client only.
bool NeedSaving(NPC npc) hook same Allows you to make a npc be saved even if it's not a townNPC and NPCID.Sets.SavesAndLoads[npc.type] is false. NOTE: A town NPC will always be saved (except the Travelling Merchant that never will). NOTE: A NPC that needs saving will not despawn naturally.
ITownNPCProfile ModifyTownNPCProfile(NPC npc) hook same Allows you to set the town NPC profile that a given NPC uses.
void SaveData(NPC npc, TagCompound tag) hook same Allows you to save custom data for the given npc. NOTE: The provided tag is always empty by default, and is provided as an argument only for the sake of convenience and optimization. NOTE: Try to only save data that isn't default values. NOTE: The npc may be saved even if NeedSaving returns false and npc is not a townNPC, if another mod returns true on NeedSaving.
void LoadData(NPC npc, TagCompound tag) hook same Allows you to load custom data that you have saved for the given npc.
void ResetEffects(NPC npc) hook same This is where you reset any fields you add to your subclass to their default states. This is necessary in order to reset your fields if they are conditionally set by a tick update but the condition is no longer satisfied. Called on the server and clients.
bool PreAI(NPC npc) hook same Allows you to determine how any NPC behaves. Return false to stop the vanilla AI and the AI hook from being run. Returns true by default. Called on the server and clients.
void AI(NPC npc) hook same Allows you to determine how any NPC behaves. This will only be called if PreAI returns true. Called on the server and clients.
void PostAI(NPC npc) hook same Allows you to determine how any NPC behaves. This will be called regardless of what PreAI returns. Called on the server and clients.
void FindFrame(NPC npc, int frameHeight) hook same Allows you to modify the frame from an NPC's texture that is drawn, which is necessary in order to animate NPCs. Called on the server and clients.
void HitEffect(NPC npc, HitInfo hit) hook same Allows you to make things happen whenever an NPC is hit, such as creating dust or gores. Called on local, server, and remote clients. Usually when something happens when an npc dies such as item spawning, you use NPCLoot, but you can use HitEffect paired with a check for if (npc.life <= 0) to do client-side death effects, such as spawning dust, gore, or death sounds.
void UpdateLifeRegen(NPC npc, ref int damage) hook same Allows you to make the NPC either regenerate health or take damage over time by setting lifeRegen. This is useful for implementing damage over time debuffs such as Poisoned or OnFire. Regeneration or damage will occur at a rate of half of lifeRegen per second. Essentially, modders implementing damage over time debuffs should subtract from lifeRegen a number that is twice as large as the intended damage per second. See DamageOverTimeGlobalNPC.cs for an example of this. The damage parameter is the number that appears above the NPC's head if it takes damage over time. Multiple debuffs work together by following some conventions: lifeRegen should not be assigned a number, rather it should be subtracted from. damage should only be assigned if the intended popup text is larger then its current value. Called on the server and clients.
bool CheckActive(NPC npc) hook same Whether or not to run the code for checking whether an NPC will remain active. Return false to stop the NPC from being despawned and to stop the NPC from counting towards the limit for how many NPCs can exist near a player. Returns true by default. Called on the server and clients.
bool CheckDead(NPC npc) hook same Whether or not an NPC should be killed when it reaches 0 health. You may program extra effects in this hook (for example, how Golem's head lifts up for the second phase of its fight). Return false to stop the NPC from being killed. Returns true by default. Called on the server and clients.
bool CanBeHitByItem(NPC npc, Player player, Item item) hook same Allows you to determine whether an NPC can be hit by the given melee weapon when swung. Return true to allow hitting the NPC, return false to block hitting the NPC, and return null to use the vanilla code for whether the NPC can be hit. Returns null by default. Called on the local client only.
bool CanCollideWithPlayerMeleeAttack(NPC npc, Player player, Item item, Rectangle meleeAttackHitbox) hook same Allows you to determine whether an NPC can be collided with the player melee weapon when swung. Use CanBeHitByItem instead for Guide Voodoo Doll-type effects. Called on the local client only.
void ModifyIncomingHit(NPC npc, ref HitModifiers modifiers) hook same Allows you to use a custom damage formula for when an NPC takes damage from any source. For example, you can change the way defense works or use a different crit multiplier. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. Can be called on the local client or server, depending on who is dealing damage.
void ModifyHitByItem(NPC npc, Player player, Item item, ref HitModifiers modifiers) hook same Allows you to modify the damage, knockback, etc., that an NPC takes from a melee weapon. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. Called on the local client only.
void OnHitByItem(NPC npc, Player player, Item item, HitInfo hit, int damageDone) hook same Allows you to create special effects when an NPC is hit by a melee weapon. Called on the client doing the damage.
bool CanBeHitByProjectile(NPC npc, Projectile projectile) hook same Allows you to determine whether an NPC can be hit by the given projectile. Return true to allow hitting the NPC, return false to block hitting the NPC, and return null to use the vanilla code for whether the NPC can be hit. Returns null by default. Can be called on the local client or server, depending on who owns the projectile.
void ModifyHitByProjectile(NPC npc, Projectile projectile, ref HitModifiers modifiers) hook same Allows you to modify the damage, knockback, etc., that an NPC takes from a projectile. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. Can be called on the local client or server, depending on who owns the projectile.
void OnHitByProjectile(NPC npc, Projectile projectile, HitInfo hit, int damageDone) hook same Allows you to create special effects when an NPC is hit by a projectile. Can be called on the local client or server, depending on who owns the projectile.
bool CanHitPlayer(NPC npc, Player target, ref int cooldownSlot) hook same Allows you to determine whether an NPC can hit the given player. Return false to block the NPC from hitting the target. Returns true by default. CooldownSlot determines which of the player's cooldown counters (ImmunityCooldownID) to use, and defaults to -1 (General). Called on the local client only.
void ModifyHitPlayer(NPC npc, Player target, ref HurtModifiers modifiers) hook same Allows you to modify the damage, etc., that an NPC does to a player. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. Called on the local client only.
void OnHitPlayer(NPC npc, Player target, HurtInfo hurtInfo) hook same Allows you to create special effects when an NPC hits a player (for example, inflicting debuffs). Called on the local client only.
bool CanHitNPC(NPC npc, NPC target) hook same Allows you to determine whether an NPC can hit the given friendly NPC. Return false to block the NPC from hitting the target, and return true to use the vanilla code for whether the target can be hit. Returns true by default. Called in single player or on the server only.
bool CanBeHitByNPC(NPC npc, NPC attacker) hook same Allows you to determine whether a friendly NPC can be hit by an NPC. Return false to block the attacker from hitting the NPC, and return true to use the vanilla code for whether the target can be hit. Returns true by default. Called in single player or on the server only.
void ModifyHitNPC(NPC npc, NPC target, ref HitModifiers modifiers) hook same Allows you to modify the damage, knockback, etc., that an NPC does to a friendly NPC. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. Called in single player or on the server only.
void OnHitNPC(NPC npc, NPC target, HitInfo hit) hook same Allows you to create special effects when an NPC hits a friendly NPC. Called in single player or on the server only.
void ModifyNPCLoot(NPC npc, NPCLoot npcLoot) hook same Allows you to add and modify NPC loot tables to drop on death and to appear in the Bestiary. The Basic NPC Drops and Loot 1.4 Guide explains how to use this hook to modify npc loot. This hook only runs once per npc type during mod loading, any dynamic behavior must be contained in the rules themselves.
void ModifyGlobalLoot(GlobalLoot globalLoot) hook same Allows you to add and modify global loot rules that are conditional, i.e. vanilla's biome keys and souls. The Basic NPC Drops and Loot 1.4 Guide explains how to use this hook to modify npc loot.
bool PreKill(NPC npc) hook same Allows you to determine whether or not this NPC will do anything upon death (besides dying). This method can also be used to dynamically prevent specific item loot using blockLoot, but editing the drop rules themselves is usually the better approach. Returning false will skip dropping loot, the OnKill methods, and logic setting boss flags (DoDeathEvents). Returns true by default. Called in single player or on the server only.
void OnKill(NPC npc) hook same Allows you to make things happen when an NPC dies (for example, setting ModSystem fields). For client-side effects, such as dust, gore, and sounds, see HitEffect. Boss flags are set after this, so this method is suitable to check if a boss defeated flag is false to detect if this is the first victory against that boss. Called in single player or on the server only. Most item drops should be done via drop rules registered in ModifyNPCLoot or ModifyGlobalLoot. Some dynamic NPC drops, such as additional hearts, are more suited for OnKill instead. MinionBossMinion.cs shows an example of an NPC that drops additional hearts. See lastInteraction and Player who killed NPC wiki section as well for determining which players attacked or killed this NPC.
void EditSpawnRate(Player player, ref int spawnRate, ref int maxSpawns) hook same Allows you to modify the chance of NPCs spawning around the given player and the maximum number of NPCs that can spawn around the player. Lower spawnRates mean a higher chance for NPCs to spawn. Called in single player or on the server only.
void EditSpawnRange(Player player, ref int spawnRangeX, ref int spawnRangeY, ref int safeRangeX, ref int safeRangeY) hook same Allows you to modify the range at which NPCs can spawn around the given player. The spawnRanges determine that maximum distance NPCs can spawn from the player, and the safeRanges determine the minimum distance. Called in single player or on the server only.
void EditSpawnFlags(Spawner spawner) hook same Allows you to modify natural spawn flags for the given player before spawn rate, spawn range, and spawn tile are determined. Use this for player-level spawn context that should affect those later steps, such as biome, safe wall, or invasion flags. For example, a modded safe-zone effect could set spawner.noWorms = true before vanilla spawn logic uses that flag. Called in single player or on the server only.
void EditSpawnInfo(Spawner spawner) hook same Allows you to modify natural spawn information after the spawn tile has been chosen and before the spawn pool is evaluated. Use this for tile-level spawn context, such as water, granite, marble, spider cave, underground desert, spawn tile type, or spawn wall type. For example, a modded tile could set spawner.nearGranite = true so later SpawnChance and EditSpawnPool logic sees the chosen tile as granite-like. Called in single player or on the server only.
void EditSpawnPool(IDictionary<int, float> pool, Spawner spawner) hook same Allows you to control which NPCs can spawn and how likely each one is to spawn. The pool parameter maps NPC types to their spawning weights (likelihood to spawn compared to other NPCs). A type of 0 in the pool represents the default vanilla NPC spawning. Called in single player or on the server only.
void EditSpawnPool(IDictionary<int, float> pool, NPCSpawnInfo spawnInfo) hook differs Allows you to control which NPCs can spawn and how likely each one is to spawn. The pool parameter maps NPC types to their spawning weights (likelihood to spawn compared to other NPCs). A type of 0 in the pool represents the default vanilla NPC spawning. Called in single player or on the server only. tML: void EditSpawnPool(IDictionary<int, float> pool, Spawner spawner)
void SpawnNPC(int npc, int tileX, int tileY) hook same Allows you to customize an NPC (for example, its position or ai array) after it naturally spawns and before it is synced between servers and clients. As of right now, this only works for modded NPCs. Called in single player or on the server only.
bool CanChat(NPC npc) hook same Allows you to determine whether this NPC can talk with the player. Return true to allow talking with the player, return false to block this NPC from talking with the player, and return null to use the vanilla code for whether the NPC can talk. Returns null by default. Called on the local client only.
void GetChat(NPC npc, ref string chat) hook same Allows you to modify the chat message of any NPC that the player can talk to. Called on the local client only.
void ModifyNPCNameList(NPC npc, List<string> nameList) hook same Allows you to modify the list of names available to the given town NPC.
void RegisterChatButtons(NPC npc, NPCInteractionList interactions) hook same Allows you to register chat buttons for this NPC. Use interactions to register new buttons. The "Close", "Happiness", and "Housing" buttons will automatically be registered before the buttons registered here. An NPC can only have 32 chat buttons shown at one time.
bool PreChatButtonClicked(NPC npc, NPCInteraction interaction) hook same Allows you to determine if something can happen whenever a button is clicked on this NPC's chat window. Return false to prevent the normal code for this button from running. Returns true by default. Called on the local client only.
void OnChatButtonClicked(NPC npc, NPCInteraction interaction) hook same Allows you to make something happen whenever a button is clicked on this NPC's chat window. Called on the local client only.
void ModifyShop(NPCShop shop) hook same Allows you to modify existing shop. Be aware that this hook is called just one time during loading. The traveling merchant shop is passed here, but the per visit (info) entries cannot be modified here. Use SetupTravelShop instead.
void ModifyActiveShop(NPC npc, string shopName, Item[] items) hook same Allows you to modify the contents of a shop whenever player opens it. If possible, use ModifyShop instead, to reduce mod conflicts and improve compatibility. Also note that unused slots in items are null while IsAir entries are entries that have a reserved slot (SlotReserved) but did not have their conditions met. These should not be overwritten. Called on the local client only.
void SetupTravelShop(int[] shop, ref int nextSlot) hook same Allows you to add items to the traveling merchant's shop. Add an item by setting shop[nextSlot] to the ID of the item you are adding then incrementing nextSlot. In the end, nextSlot must have a value of 1 greater than the highest index in shop that represents an item ID. If you want to remove an item, you will have to be familiar with programming. Called in single player or on the server only.
void ModifyNPCHappiness(NPC npc, int primaryPlayerBiome, ShopHelper shopHelperInstance, bool[] nearbyNPCsByType) hook only here Changes how an NPC feels about a biome or a neighbour. Phone: Runs when the game works out the shop price, and primaryPlayerBiome is always 0. In tModLoader the call is commented out.
void TownNPCAttackStrength(NPC npc, ref int damage, ref float knockback) hook same Allows you to determine the damage and knockback of a town NPC's attack before the damage is scaled. (More information on scaling in GlobalNPC.BuffTownNPCs.) Called on the server and clients.
void TownNPCAttackCooldown(NPC npc, ref int cooldown, ref int randExtraCooldown) hook same Allows you to determine the cooldown between each of a town NPC's attack. The cooldown will be a number greater than or equal to the first parameter, and less then the sum of the two parameters. Called on the server and clients.
void TownNPCAttackProj(NPC npc, ref int projType, ref int attackDelay) hook same Allows you to determine the projectile type of a town NPC's attack, and how long it takes for the projectile to actually appear. This hook is only used when the town NPC has an attack type of 0 (throwing), 1 (shooting), or 2 (magic). Called on the server and clients.
void TownNPCAttackProjSpeed(NPC npc, ref float multiplier, ref float gravityCorrection, ref float randomOffset) hook same Allows you to determine the speed at which a town NPC throws a projectile when it attacks. Multiplier is the speed of the projectile, gravityCorrection is how much extra the projectile gets thrown upwards, and randomOffset allows you to randomize the projectile's velocity in a square centered around the original velocity. This hook is only used when the town NPC has an attack type of 0 (throwing), 1 (shooting), or 2 (magic). Called on the server and clients.
void TownNPCAttackShoot(NPC npc, ref bool inBetweenShots) hook same Allows you to tell the game that a town NPC has already created a projectile and will still create more projectiles as part of a single attack so that the game can animate the NPC's attack properly. Only used when the town NPC has an attack type of 1 (shooting). Called on the server and clients.
void TownNPCAttackMagic(NPC npc, ref float auraLightMultiplier) hook same Allows you to control the brightness of the light emitted by a town NPC's aura when it performs a magic attack. Only used when the town NPC has an attack type of 2 (magic) Called on the server and clients.
void TownNPCAttackSwing(NPC npc, ref int itemWidth, ref int itemHeight) hook same Allows you to determine the width and height of the item a town NPC swings when it attacks, which controls the range of the NPC's swung weapon. Only used when the town NPC has an attack type of 3 (swinging). Called on the server and clients.
void DrawTownAttackGun(NPC npc, ref Texture2D item, ref Rectangle itemFrame, ref float scale, ref int horizontalHoldoutOffset) hook same Allows you to customize how a town NPC's weapon is drawn when the NPC is shooting (the NPC must have an attack type of 1). scale is a multiplier for the item's drawing size, item is the Texture2D instance of the item to be drawn, itemFrame is the section of the texture to draw, and horizontalHoldoutOffset is how far away the item should be drawn from the NPC. Called on the server and clients.
void DrawTownAttackSwing(NPC npc, ref Texture2D item, ref Rectangle itemFrame, ref int itemSize, ref float scale, ref Vector2 offset) hook same Allows you to customize how this town NPC's weapon is drawn when this NPC is swinging it (this NPC must have an attack type (AttackType) of 3). item is the Texture2D instance of the item to be drawn, itemFrame is the section of the texture to draw, itemSize is the width and height of the item's hitbox (the same values for TownNPCAttackSwing), scale is the multiplier for the item's drawing size, and offset is the offset from which to draw the item from its normal position. The item texture can be any texture, but if it is an item texture you can use GetItemDrawFrame to set item and itemFrame easily. Called on all clients.

IItemDropRule

interface Terraria.GameContent.ItemDropRules.IItemDropRule

A drop rule. Build your own by implementing it, or use ItemDropRule.

Member Kind tModLoader What it does
List<IItemDropRuleChainAttempt> ChainedRules hook same The rules chained to this one.
bool CanDrop(DropAttemptInfo info) hook same Whether it can drop now.
ItemDropAttemptResult TryDroppingItem(DropAttemptInfo info) hook same Tries to drop, and says how it went.
void ReportDroprates(List<DropRateInfo> drops, DropRateInfoChainFeed ratesInfo) hook same Fills the chances the bestiary shows.

IItemDropRuleChainAttempt

interface Terraria.GameContent.ItemDropRules.IItemDropRuleChainAttempt

A rule chained to another, run only if the first one meets its test.

Member Kind tModLoader What it does
IItemDropRule RuleToChain hook same The next rule.
bool CanChainIntoRule(ItemDropAttemptResult parentResult) hook same Whether the next rule runs, after this result.
void ReportDroprates(float personalDropRate, List<DropRateInfo> drops, DropRateInfoChainFeed ratesInfo) hook same Fills the bestiary's chance for the chain.

IItemDropRuleCondition

interface Terraria.GameContent.ItemDropRules.IItemDropRuleCondition : IProvideItemConditionDescription

A condition for a drop rule.

Member Kind tModLoader What it does
bool CanDrop(DropAttemptInfo info) hook same Whether it holds now.
bool CanShowItemDropInUI() hook same Whether the drop shows in the bestiary.

ITownNPCProfile

interface Terraria.GameContent.ITownNPCProfile

Chooses a town NPC's texture, head, name and variant.

Member Kind tModLoader What it does
int RollVariation() hook same Picks a variant for a new NPC.
string GetNameForVariant(NPC npc) hook same The name for this variant, or null for a random name.
Asset<Texture2D> GetTextureNPCShouldUse(NPC npc) hook same The texture for this NPC now.
int GetHeadTextureIndex(NPC npc) hook same The head's slot in TextureAssets.NpcHead.

InvasionEnemy

record Terraria.ModLoader.InvasionEnemy · only in Bunny Loader

An enemy of an invasion wave: its NPC type, how often it spawns and the points it gives.

InvasionLoader

static class Terraria.ModLoader.InvasionLoader · only in Bunny Loader

Runs invasions: Start, Stop, AddPoints, and reads the wave and progress. Keeps the host and clients in sync.

Member Kind tModLoader What it does
IReadOnlyList<ModInvasion> All static property only here Every invasion.
ModInvasion Active static property only here The running invasion, or null.
int Wave static property only here The current wave, from 0.
int Progress static property only here Points earned in this wave.
int ProgressMax static property only here Points to clear this wave.
bool IsDowned(ModInvasion invasion) static method only here Whether this invasion was beaten in this world.
bool CanStart(ModInvasion invasion) static method only here Whether it could start now.
bool Start(ModInvasion invasion) static method only here Starts it, on any side. Returns false if it was refused.
void AddPoints(int points) static method only here Adds wave points.
void Stop(bool success) static method only here Ends the invasion, as a win or a loss.

InvasionWave

record Terraria.ModLoader.InvasionWave · only in Bunny Loader

One wave of an invasion: the points to clear it and its enemies.

ModBossBar

abstract class Terraria.ModLoader.ModBossBar : ModTexturedType

A class that is used to create custom boss health bars for modded and vanilla NPCs.

Member Kind tModLoader What it does
int Type property only here The bar's number.
float Life property same The life shown, set in ValidateAndCollectNecessaryInfo.
float LifeMax property same The largest life shown.
float Shield property same The shield shown.
float ShieldMax property same The largest shield shown.
Asset<Texture2D> GetIconTexture(ref Rectangle iconFrame) hook same Allows you to specify the icon texture, and optionally the frame it should be displayed on. The frame defaults to the entire texture otherwise.
bool ModifyInfo(ref BigProgressBarInfo info, ref float life, ref float lifeMax, ref float shield, ref float shieldMax) hook same Allows you to handle the logic for when and how this ModBossBar should work. You want to override this if you have a multi-segment NPC. Returns null by default. Failing to return false otherwise will lead to your bar being displayed at wrong times. Return null to let the basic logic run after this hook is called (index validity check and assigning lifePercent to match the health of the NPC) and then allowing it to be drawn. Return true to allow this ModBossBar to be drawn. Return false to prevent this ModBossBar from being drawn so that the game will try to pick a different one.
bool PreDraw(SpriteBatch spriteBatch, NPC npc, ref BossBarDrawParams drawParams) hook same Allows you to draw things before the default draw code is ran. Return false to prevent drawing the ModBossBar. Returns true by default.
void PostDraw(SpriteBatch spriteBatch, NPC npc, BossBarDrawParams drawParams) hook same Allows you to draw things after the bar has been drawn. skipped is true if you or another mod has skipped drawing the bar in PreDraw (possibly hiding it or in favor of new visuals).
bool ValidateAndCollectNecessaryInfo(ref BigProgressBarInfo info) method same Whether the bar shows, reading the NPC.
void Draw(ref BigProgressBarInfo info, SpriteBatch spriteBatch) method not here Not implemented. Use PreDraw and PostDraw.

ModBossBarStyle

abstract class Terraria.ModLoader.ModBossBarStyle : ModType

A class that is used to swap out the entire boss bar display system with your own implementation

Member Kind tModLoader What it does
bool IsSelected property same Checks if the selected style matches this ModBossBarStyle.
string DisplayName hook same Controls the name that shows up in the menu selection. If not overridden, it will use this mod's display name.
bool PreventUpdate hook same Return true to skip update code for boss bars. Useful if you want to use your own code for finding out which NPCs to track. Returns false by default.
bool PreventDraw hook same Return true to skip draw code for boss bars. Useful if you want to use your own code for drawing boss bars. Returns false by default.
void Update(IBigProgressBar currentBar, ref BigProgressBarInfo info) hook same Runs after update code for boss bars (skipped if PreventUpdate returns true), can be used to identify which NPCs to draw.
void OnSelected() hook same Called when this ModBossBarStyle is selected
void OnDeselected() hook same Called when this ModBossBarStyle is deselected
void Draw(SpriteBatch spriteBatch, IBigProgressBar currentBar, BigProgressBarInfo info) hook same Runs after draw code for boss bars (skipped if PreventDraw returns true), can be used to draw your own bars, or reinvoke draw for currently selected-to-draw bar

ModEmoteBubble

abstract class Terraria.ModLoader.ModEmoteBubble : ModType<EmoteBubble, ModEmoteBubble>

Represents an emote. Emotes are typically used by players or NPC. Players can use the emotes menu or chat commands to display an emote, while town NPC spawn emotes when talking to each other.

Member Kind tModLoader What it does
string Texture hook same The file name of this emote's texture file in the mod loader's file space.
int Type property same The internal ID of this EmoteBubble.
EmoteBubble EmoteBubble property same This is the EmoteBubble instance.
string LocalizationCategory hook same The folder of this content in the localization files.
LocalizedText Command hook same This is the name that will show up as the emote command. Must be lowercase.
EmoteBubble CreateTemplateEntity() override same Creates the bubble the instance works on.
void AddToCategory(int categoryId) method same Allows you to add this emote to a specific vanilla category. This should only be called in SetStaticDefaults
bool IsUnlocked() hook same Allows you to determine whether or not this emote can be seen in emotes menu. Returns true by default. Do note that this doesn't effect emote command and NPC using.
void OnSpawn() hook same Gets called when your emote bubble spawns in world.
bool UpdateFrame() hook same Allows you to modify the frame of this emote bubble. Return false to stop vanilla frame update code from running. Returns true by default.
bool UpdateFrameInEmoteMenu(ref int frameCounter) hook same Allows you to modify the frame of this emote bubble which displays in emotes menu. Return false to stop vanilla frame update code from running. Returns true by default. Do note that you should NEVER use the EmoteBubble field in this method because it's null.
bool PreDraw(SpriteBatch spriteBatch, Texture2D texture, Vector2 position, Rectangle frame, Vector2 origin, SpriteEffects spriteEffects) hook same Allows you to draw things behind this emote bubble, or to modify the way this emote bubble is drawn. Return false to stop the game from drawing the emote bubble (useful if you're manually drawing the emote bubble). Returns true by default.
void PostDraw(SpriteBatch spriteBatch, Texture2D texture, Vector2 position, Rectangle frame, Vector2 origin, SpriteEffects spriteEffects) hook same Allows you to draw things in front of this emote bubble. This method is called even if PreDraw returns false.
Rectangle GetFrame() hook same Allows you to modify the frame rectangle for drawing this emote. Useful for emote bubbles that share the same texture.
Rectangle GetFrameInEmoteMenu(int frame, int frameCounter) hook same Allows you to modify the frame rectangle for drawing this emote in emotes menu. Useful for emote bubbles that share the same texture.
bool PreDrawInEmoteMenu(SpriteBatch spriteBatch, EmoteButton uiEmoteButton, Vector2 position, Rectangle frame, Vector2 origin) hook not here Allows you to draw things behind this emote bubble that displays in emotes menu, or to modify the way this emote bubble is drawn. Return false to stop the game from drawing the emote bubble (useful if you're manually drawing the emote bubble). Returns true by default. Do note that you should NEVER use the EmoteBubble field in this method because it's null.
void PostDrawInEmoteMenu(SpriteBatch spriteBatch, EmoteButton uiEmoteButton, Vector2 position, Rectangle frame, Vector2 origin) hook not here Allows you to draw things in front of this emote bubble. This method is called even if PreDraw returns false. Do note that you should NEVER use the EmoteBubble field in this method because it's null.

ModInvasion

abstract class Terraria.ModLoader.ModInvasion : ModType · only in Bunny Loader

A wave-based event that uses the game's progress bar. See Invasions. Your subclass lists the waves.

Member Kind tModLoader What it does
int Type property only here The invasion's number.
string LocalizationCategory hook only here The folder of this content in the localization files.
LocalizedText DisplayName hook only here The name shown to the player, as localized text.
string IconTexture hook only here The icon of the bar. By default <Texture>_Icon.
Color MessageColor hook only here The color of its messages in chat.
int Music hook only here The music while it runs, as a MusicID or MusicLoader.GetMusicSlot. -1 leaves the music alone.
IList<InvasionWave> Waves hook only here The waves. Each has its points and enemies.
int SpawnRate hook only here The spawn rate while it runs. Lower is faster.
int MaxSpawns hook only here How many enemies at once.
bool CanStart() hook only here Whether it may start now.
bool CanSpawn(Player player) hook only here Whether enemies spawn around this player.
bool ShouldFail() hook only here Whether it ends in a loss now.
int PointsFor(NPC npc, InvasionWave wave) hook only here Points for killing this NPC. 0 to count nothing.
int ScalePoints(int points, int players) hook only here Points per wave with more players.
void OnStart() hook only here Runs once at the start.
void OnWaveStart(int wave) hook only here Runs at the start of each wave.
void OnWaveComplete(int wave) hook only here Runs at the end of each wave.
void OnComplete() hook only here Runs when it is won.
void OnFail() hook only here Runs when it is lost.
void Update() hook only here Runs every tick while it is active.

ModNPC

abstract class Terraria.ModLoader.ModNPC : ModType<NPC, ModNPC>

This class serves as a place for you to place all your properties and hooks for each NPC. To use it, simply create a new class deriving from this one. Implementations will be registered automatically. The Basic NPC Guide teaches the basics of making a modded NPC.

Member Kind tModLoader What it does
ref NPC NPC property differs The NPC object that this ModNPC controls. tML: NPC NPC
int Type property same Shorthand for NPC.type;
int AIType property same Determines which type of vanilla NPC this ModNPC will copy the behavior (AI) of. Leave as 0 to not copy any behavior. Defaults to 0.
int AnimationType property same Determines which type of vanilla NPC this ModNPC will copy the animation/framing logic of, which includes checks to sets such as and , and others. For example, selecting the Guide's type will copy how many frames, extra frames, and attack frames the Guide has, and use those value for animation of this NPC. This is entirely based off of type and not the ModNPC instance itself; so be cautious if you change this NPC's type.
int Music property same The ID of the music that plays when this NPC is on or near the screen. Defaults to -1, which means music plays normally. See swapMusic for information about playing alternate music when the Otherworld soundtrack is enabled.
int Banner property same The type of NPC that this NPC will be considered as when determining banner drops and banner bonuses. Also known as the BannerID. By default this will be 0, which means this NPC is not associated with any banner. To give your NPC its own banner, set this field to the NPC's type and also set BannerItem: Banner = Type; BannerItem = ModContent.ItemType(); For NPC with multiple parts, such as worms, be sure to set this to the same value for each ModNPC. Typically the head NPC type is used as the common Banner value. ExampleWorm.cs is an example of this: // In ExampleWormBody.SetDefaults: Banner = ModContent.NPCType(); For NPC that are variants of each other, it is also useful to share a Banner value so that each variant counts towards the same banner kill count rather than each having their own banner drop. PartyZombie.cs does this and shares the vanilla Zombie banner. By doing this it is affected by the Zombie banner and counts towards dropping it as well. To retrieve and use a vanilla banner value, use the NPCtoBanner method: Banner = Item.NPCtoBanner(NPCID.Zombie);
int BannerItem property same The item type this NPC drops after some number of it is defeated. The exact number can be customized by using KillsToBanner and defaults to 50. For any ModNPC whose Banner field is set to the type of this NPC, that ModNPC will drop this banner. Must be set along with Banner. If querying the banner item drop for a specific NPC that you know has an assigned banner, you'll need to use the following for accurate results since BannerItem isn't necessarily assigned for npc sharing a banner: Item.BannerToItem(Item.NPCtoBanner(npc.BannerID()));
SceneEffectPriority SceneEffectPriority property same The priority of the music that plays when this NPC is on or near the screen.
int[] SpawnModBiomes property same The ModBiome Types associated with this NPC spawning, if applicable. Used in Bestiary. Vanilla biomes are added to the bestiary via SetBestiary directly.
string LocalizationCategory hook same The folder of this content in the localization files.
LocalizedText DisplayName hook same The translations for the display name of this NPC.
string Texture hook same The file name of this type's texture file in the mod loader's file space, without the file extension. The resulting Asset can be retrieved using Npc indexed by Type if needed. You can use a vanilla texture by returning $"Terraria/Images/NPC_{NPCID.NPCNameHere}"
string BossHeadTexture hook same This file name of this NPC's boss head texture file, to be used in autoloading. This texture will be automatically loaded if AutoloadBossHead annotates this class, and AddBossHeadTexture can be used to register additional boss head textures if needed for a multi-stage boss, for example. (See also BossHeadSlot) Defaults to Texture followed by "_Head_Boss".
int DrawOffsetY property differs The vertical offset used for drawing this NPC. Defaults to 0. tML: float DrawOffsetY
bool TownNPCStayingHomeless property same Setting this to true will make the NPC not appear in the housing menu nor make it find an house. Phone: The NPC stays out of the phone's housing list and of the free house.
void SetDefaults() hook same Allows you to set all your NPC's properties, such as width, damage, aiStyle, lifeMax, etc.
void OnSpawn(IEntitySource source) hook same Gets called when your NPC spawns in world Called in single player or on the server only.
void ApplyDifficultyAndPlayerScaling(int numPlayers, float balance, float bossAdjustment) hook same Allows you to customize this NPC's stats when the difficulty is expert or higher. This runs after value, lifeMax, damage, knockBackResist have been adjusted for the current difficulty, (expert/master/FTW) It is common to multiply lifeMax by the balance factor, and sometimes adjust knockbackResist. Eg: lifeMax = (int)(lifeMax * balance * bossAdjustment)
void ResetEffects() hook same This is where you reset any fields you add to your subclass to their default states. This is necessary in order to reset your fields if they are conditionally set by a tick update but the condition is no longer satisfied. (Note: This hook is only really useful for GlobalNPC, but is included in ModNPC for completion.) Called on the server and clients.
bool PreAI() hook same Allows you to determine how this NPC behaves. Return false to stop the vanilla AI and the AI hook from being run. Returns true by default. Called on the server and clients.
void AI() hook same Allows you to determine how this NPC behaves. This will only be called if PreAI returns true. Called on the server and clients.
void PostAI() hook same Allows you to determine how any NPC behaves. This will be called regardless of what PreAI returns. Called on the server and remote clients.
void FindFrame(int frameHeight) hook same Allows you to modify the frame from this NPC's texture that is drawn, which is necessary in order to animate NPCs. Called on the server and clients.
void HitEffect(HitInfo hit) hook same Allows you to make things happen whenever this NPC is hit, such as creating dust or gores. Called on local, server, and remote clients. Usually when something happens when an NPC dies such as item spawning, you use NPCLoot, but you can use HitEffect paired with a check for if (NPC.life <= 0) to do client-side death effects, such as spawning dust, gore, or death sounds.
void UpdateLifeRegen(ref int damage) hook same Allows you to make the NPC either regenerate health or take damage over time by setting lifeRegen. This is useful for implementing damage over time debuffs such as Poisoned or OnFire. Regeneration or damage will occur at a rate of half of lifeRegen per second. Essentially, modders implementing damage over time debuffs should subtract from lifeRegen a number that is twice as large as the intended damage per second. See DamageOverTimeGlobalNPC.cs for an example of this. The damage parameter is the number that appears above the NPC's head if it takes damage over time. Multiple debuffs work together by following some conventions: lifeRegen should not be assigned a number, rather it should be subtracted from. damage should only be assigned if the intended popup text is larger then its current value. Called on the server and clients.
bool CheckActive() hook same Whether or not to run the code for checking whether this NPC will remain active. Return false to stop this NPC from being despawned and to stop this NPC from counting towards the limit for how many NPCs can exist near a player. Returns true by default. See also DoesntDespawnToInactivityAndCountsNPCSlots for an option that still counts towards NPC spawn limits. Called on the server and clients.
bool CheckDead() hook same Whether or not this NPC should be killed when it reaches 0 health. You may program extra effects in this hook (for example, how Golem's head lifts up for the second phase of its fight). Return false to stop this NPC from being killed. Returns true by default. Called on the server and clients.
bool CanBeHitByItem(Player player, Item item) hook same Allows you to determine whether this NPC can be hit by the given melee weapon when swung. Return true to allow hitting the NPC, return false to block hitting the NPC, and return null to use the vanilla code for whether the NPC can be hit. Returns null by default. Called on the local client only.
bool CanCollideWithPlayerMeleeAttack(Player player, Item item, Rectangle meleeAttackHitbox) hook same Allows you to determine whether an NPC can be collided with the player melee weapon when swung. Use CanBeHitByItem instead for Guide Voodoo Doll-type effects. Called on the local client only.
void ModifyIncomingHit(ref HitModifiers modifiers) hook same Allows you to use a custom damage formula for when this NPC takes damage from any source. For example, you can change the way defense works or use a different crit multiplier. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. Can be called on the local client or server, depending on who is dealing damage.
void ModifyHitByItem(Player player, Item item, ref HitModifiers modifiers) hook same Allows you to modify the damage, knockback, etc., that this NPC takes from a melee weapon. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. The final hit values such as the final damage can only be retrieved from the HitInfo in the OnHitByItem hook. Called on the local client only.
void OnHitByItem(Player player, Item item, HitInfo hit, int damageDone) hook same Allows you to create special effects when this NPC is hit by a melee weapon. Changes to the hit such as the damage must be done by modifying the HitModifiers properties in the ModifyHitByItem hook. Called on the client doing the damage.
bool CanBeHitByProjectile(Projectile projectile) hook same Allows you to determine whether this NPC can be hit by the given projectile. Return true to allow hitting the NPC, return false to block hitting the NPC, and return null to use the vanilla code for whether the NPC can be hit. Returns null by default. Can be called on the local client or server, depending on who owns the projectile.
void ModifyHitByProjectile(Projectile projectile, ref HitModifiers modifiers) hook same Allows you to modify the damage, knockback, etc., that this NPC takes from a projectile. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. The final hit values such as the final damage can only be retrieved from the HitInfo in the OnHitByProjectile hook. Can be called on the local client or server, depending on who owns the projectile.
void OnHitByProjectile(Projectile projectile, HitInfo hit, int damageDone) hook same Allows you to create special effects when this NPC is hit by a projectile. Changes to the hit such as the damage must be done by modifying the HitModifiers properties in the ModifyHitByProjectile hook. Can be called on the local client or server, depending on who owns the projectile.
bool CanHitPlayer(Player target, ref int cooldownSlot) hook same Allows you to determine whether this NPC can hit the given player. Return false to block this NPC from hitting the target. Returns true by default. CooldownSlot determines which of the player's cooldown counters (ImmunityCooldownID) to use, and defaults to -1 (General). Called on the local client only.
void ModifyHitPlayer(Player target, ref HurtModifiers modifiers) hook same Allows you to modify the damage, etc., that this NPC does to a player. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. The final hit values such as the final damage can only be retrieved from the HurtInfo in the OnHitPlayer hook. Called on the local client only.
void OnHitPlayer(Player target, HurtInfo hurtInfo) hook same Allows you to create special effects when this NPC hits a player (for example, inflicting debuffs). Changes to the hit such as the damage must be done by modifying the HurtModifiers properties in the ModifyHitPlayer hook. Called on the local client only.
bool CanHitNPC(NPC target) hook same Allows you to determine whether this NPC can hit the given friendly NPC. Return false to block the NPC from hitting the target, and return true to use the vanilla code for whether the target can be hit. Returns true by default. Called in single player or on the server only.
bool CanBeHitByNPC(NPC attacker) hook same Allows you to determine whether a friendly NPC can be hit by an NPC. Return false to block the attacker from hitting the NPC, and return true to use the vanilla code for whether the target can be hit. Returns true by default. Called in single player or on the server only.
void ModifyHitNPC(NPC target, ref HitModifiers modifiers) hook same Allows you to modify the damage, knockback, etc., that this NPC does to a friendly NPC. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. The final hit values such as the final damage can only be retrieved from the HitInfo in the OnHitNPC hook. Called in single player or on the server only.
void OnHitNPC(NPC target, HitInfo hit) hook same Allows you to create special effects when this NPC hits a friendly NPC. Changes to the hit such as the damage must be done by modifying the HitModifiers properties in the ModifyHitNPC hook. Called in single player or on the server only.
void SendExtraAI(BinaryWriter writer) hook same If you are storing AI information outside of the NPC.ai array, use this to send that AI information between clients and servers, which will be handled in ReceiveExtraAI. Called whenever SyncNPC is successfully sent, for example on NPC creation, on player join, or whenever NPC.netUpdate is set to true in the update loop for that tick. Only called on the server.
void ReceiveExtraAI(BinaryReader reader) hook same Use this to receive information that was sent in SendExtraAI. Called whenever SyncNPC is successfully received. Only called on the client.
void BossHeadSlot(ref int index) hook same Allows you to customize the boss head texture used by an NPC based on its state. Set index to -1 to stop the texture from being displayed. Called on all clients.
void BossHeadRotation(ref float rotation) hook same Allows you to customize the rotation of this NPC's boss head icon on the map. Called on all clients.
void BossHeadSpriteEffects(ref SpriteEffects spriteEffects) hook same Allows you to flip this NPC's boss head icon on the map. Called on all clients.
Color GetAlpha(Color drawColor) hook same Allows you to determine the color and transparency in which this NPC is drawn. Return null to use the default color (normally light and buff color). Returns null by default. Called on all clients.
void DrawEffects(ref Color drawColor) hook same Allows you to add special visual effects to this NPC (such as creating dust), and modify the color in which the NPC is drawn. Called on all clients.
bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) hook same Allows you to draw things behind this NPC, or to modify the way this NPC is drawn. Substract screenPos from the draw position before drawing. Return false to stop the game from drawing the NPC (useful if you're manually drawing the NPC). Returns true by default. Called on all clients.
void PostDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) hook same Allows you to draw things in front of this NPC. Substract screenPos from the draw position before drawing. This method is called even if PreDraw returns false. Called on all clients.
void DrawBehind(int index) hook same When used in conjunction with "NPC.hide = true", allows you to specify that this NPC should be drawn behind certain elements. Add the index to one of Main.DrawCacheNPCsMoonMoon, DrawCacheNPCsOverPlayers, DrawCacheNPCProjectiles, or DrawCacheNPCsBehindNonSolidTiles. Called on all clients.
void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) hook same Allows you to set an NPC's information in the Bestiary.
int PickEmote(Player closestPlayer, List<int> emoteList, WorldUIAnchor otherAnchor) hook same Allows you to change the emote that the NPC will pick Called in single player or on the server only. Phone: otherAnchor can be null: check otherAnchor.IsNull before reading it.
void EmoteBubblePosition(ref Vector2 position, ref SpriteEffects spriteEffects) hook same Allows you to change the location and sprite direction of the emote bubble when anchored to an NPC. Called on all clients.
LocalizedText DeathMessage hook same Allows you to modify the death message of a town NPC or boss. This also affects what the dropped tombstone will say in the case of a town NPC. If substitutions are not provided by using WithFormatArgs, the NPC name will be substituted into the "{0}" placeholder. This won't have any effect if the given NPC isn't a town NPC or a boss. Returns null by default, with the text being "NPC has been defeated!" for bosses and "NPC was slain..." (or "NPC has left!" if IsTownChild or IsTownPet are set to true) for town NPCs. The keys "Announcement.HasBeenDefeated_Plural" and "Announcement.HasBeenDefeated_Single" will be useful if creating a generic boss defeat message with a custom boss name. For example: Language.GetText("Announcement.HasBeenDefeated_Plural").WithFormatArgs(Language.GetText("Mods.MyMod.NPCs.MyBoss.TheTriplets")). Make sure to use GetText instead of GetTextValue when using WithFormatArgs so the message will properly sync.
bool CanFallThroughPlatforms() hook same Allows you to determine how and when this NPC can fall through platforms and similar tiles. Return true to allow this NPC to fall through platforms, false to prevent it. Returns null by default, applying vanilla behaviors (based on aiStyle and type). Called on the server and clients.
bool ModifyCollisionData(Rectangle victimHitbox, ref int immunityCooldownSlot, ref MultipliableFloat damageMultiplier, ref Rectangle npcHitbox) hook same Allows you to modify the NPC's , damage multiplier, and hitbox. Useful for implementing dynamic damage hitboxes that change in dimensions or deal extra damage. Returns false to prevent vanilla code from running. Returns true by default. Called on the server and clients.
bool SpecialOnKill() hook same Allows you to call OnKill on your own when the NPC dies, rather then letting vanilla call it on its own. Returns false by default. Called on the server and clients.
bool ModifyDeathMessage(ref NetworkText customText, ref Color color) hook same Allows you to modify the death message of a town NPC or boss (potentially derived from DeathMessage). This also affects what the dropped tombstone will say in the case of a town NPC. The text color can also be modified. When modifying the death message, use GetFullNetName to retrieve the NPC name to use in substitutions. This is intended for more advanced use cases, you should be modifying only DeathMessage for basic usages. Return false to skip the vanilla code for sending the message. This is useful if the death message is handled by this method or if the message should be skipped for any other reason, such as if there are multiple bosses. Returns true by default.
void ModifyTypeName(ref string typeName) hook same Allows you to modify the type name of this NPC dynamically.
bool CanGoToStatue(bool toKingStatue) hook same Whether this NPC can be teleported to a King or Queen statue. Returns false by default. Called in single player or on the server only.
void OnGoToStatue(bool toKingStatue) hook same Allows you to make things happen when this NPC teleports to a King or Queen statue. Called in single player or on the server only.
bool CanBeCaughtBy(Item item, Player player) hook same Allows you to determine whether the given item can catch this NPC. Return true or false to say this NPC can or cannot be caught, respectively, regardless of vanilla rules. Returns null by default, which allows vanilla's NPC catching rules to decide the target's fate. If this returns false, OnCatchNPC is never called. NOTE: this does not classify the given item as an NPC-catching tool, which is necessary for catching NPCs in the first place. To do that, you will need to use the "CatchingTool" set in ItemID.Sets. Called on the local client only.
void OnCaughtBy(Player player, Item item, bool failed) hook same Allows you to make things happen when the given item attempts to catch this NPC. Called on the local client only.
bool UsesPartyHat() hook same Allows you to determine whether this town NPC wears a party hat during a party. Returns true by default. Called on all clients.
bool DrawHealthBar(byte hbPosition, ref float scale, ref Vector2 position) hook same Allows you to control how the health bar for this NPC is drawn. The hbPosition parameter is the same as Main.hbPosition; it determines whether the health bar gets drawn above or below the NPC by default. The scale parameter is the health bar's size. By default, it will be the normal 1f; most bosses set this to 1.5f. Return null to let the normal vanilla health-bar-drawing code to run. Return false to stop the health bar from being drawn. Return true to draw the health bar in the position specified by the position parameter (note that this is the world position, not screen position). Called on all clients.
void PartyHatPosition(ref Vector2 position, ref SpriteEffects spriteEffects) hook same Allows you to fully control the location of the party and sprite direction of the party while an NPC is wearing it. can be used instead of this hook for a constant Y offset. can be additionally be used for the Y offset for the Town NPC's animations. Called on all clients.
void ChatBubblePosition(ref Vector2 position, ref SpriteEffects spriteEffects) hook same Allows you to change the location and sprite direction of the chat bubble that shows up while hovering over a Town NPC. Called on all clients.
void ModifyHoverBoundingBox(ref Rectangle boundingBox) hook same Allows you to modify the bounding box for hovering over this NPC (affects things like whether or not its name is displayed). This hook won't be called if ShowNameOnHover is set to false. Called on the local client only.
bool PreHoverInteract(bool mouseIntersects) hook same Called when the NPC is selected via smart interact, or when the mouse is hovering over it. Right after ModifyHoverBoundingBox. Can be used to implement custom interact or hover behavior logic. By returning false, the vanilla code for town NPC chatting, drawing the chat bubble, and drawing the NPC name and life on the mouse is skipped. For example, the Old Shaking Chest NPC uses this to take a GoldenKey from the player and transform into Elder Slime. CanChat can be used to force smart interact to target this NPC despite as well, if desired. This hook won't be called if ShowNameOnHover is set to false. Called on the local client only.
bool NeedSaving() hook same Makes this ModNPC save along the world even if it's not a townNPC. Defaults to false. NOTE: A town NPC will always be saved. NOTE: A NPC that needs saving will not despawn naturally.
ITownNPCProfile TownNPCProfile() hook same Allows you to set the town NPC profile that this NPC uses. By default, returns null, meaning that the NPC doesn't use one.
void SaveData(TagCompound tag) hook same Allows you to save custom data for the given item. Allows you to save custom data for the given npc. NOTE: The provided tag is always empty by default, and is provided as an argument only for the sake of convenience and optimization. NOTE: Try to only save data that isn't default values. NOTE: The npc may be saved even if NeedSaving returns false and this is not a townNPC, if another mod returns true on NeedSaving.
void LoadData(TagCompound tag) hook same Allows you to load custom data that you have saved for this npc.
void AutoStaticDefaults() hook same Automatically sets certain static defaults. Override this if you do not want the properties to be set for you.
void ModifyNPCLoot(NPCLoot npcLoot) hook same Allows you to add and modify NPC loot tables to drop on death and to appear in the Bestiary. The Basic NPC Drops and Loot 1.4 Guide explains how to use this hook to modify NPC loot. This hook only runs once during mod loading, any dynamic behavior must be contained in the rules themselves.
bool PreKill() hook same Allows you to determine whether or not this NPC will do anything upon death (besides dying). This method can also be used to dynamically prevent specific item loot using blockLoot, but editing the drop rules themselves is usually the better approach. Returning false will skip dropping loot, the OnKill methods, and logic setting boss flags (DoDeathEvents). Returns true by default. Called in single player or on the server only.
void OnKill() hook same Allows you to make things happen when this NPC dies (for example, dropping items manually and setting ModSystem fields). Called in single player or on the server only. Most item drops should be done via drop rules registered in ModifyNPCLoot. Some dynamic NPC drops, such as additional hearts, are more suited for OnKill instead. MinionBossMinion.cs shows an example of an NPC that drops additional hearts. See lastInteraction and Player who killed NPC wiki section as well for determining which players attacked or killed this NPC. Bosses need to set flags when they are defeated, and some bosses run world generation code such as spawning new ore. MinionBossMinion.cs shows an example of these effects.
void BossLoot(ref int potionType) hook same Changes the potion a boss drops, and what else happens at its death.
void BossLoot(ref int potionType, ref int potionStack, ref int heartStack) hook same Changes the potion a boss drops, and what else happens at its death.
float SpawnChance(Spawner spawner) hook same Whether or not this NPC can spawn with the given spawning conditions. Return the weight for the chance of this NPC to spawn compared to vanilla mobs. All vanilla mobs combined have a total weight of 1. Returns 0 by default, which disables natural spawning. Remember to always use Player and not LocalPlayer when checking Player or ModPlayer fields, otherwise your mod won't work in Multiplayer. Called in single player or on the server only.
float SpawnChance(NPCSpawnInfo spawnInfo) hook differs Whether or not this NPC can spawn with the given spawning conditions. Return the weight for the chance of this NPC to spawn compared to vanilla mobs. All vanilla mobs combined have a total weight of 1. Returns 0 by default, which disables natural spawning. Remember to always use Player and not LocalPlayer when checking Player or ModPlayer fields, otherwise your mod won't work in Multiplayer. Called in single player or on the server only. tML: float SpawnChance(Spawner spawner)
int SpawnNPC(int tileX, int tileY) hook same Allows you to customize how this NPC is created when it naturally spawns (for example, its position or ai array). Return the return value of NPC.NewNPC. By default this method spawns this NPC on top of the tile at the given coordinates. Called in single player or on the server only.
string HeadTexture hook same The file name of this NPC's head texture file, to be used in autoloading. This texture will be automatically loaded if AutoloadHead annotates this class, and AddNPCHeadTexture can be used to register additional head textures if needed for a shimmered Town NPC variant, for example. Defaults to Texture followed by "_Head".
bool CanTownNPCSpawn(int numTownNPCs) hook same Whether or not the conditions have been met for this town NPC to be able to move into town. For example, the Demolitionist requires that any player has an explosive. Town NPC spawn conditions typically check if specific bosses have been defeated (downedGolemBoss), the npc has been "saved" somewhere in the world, or any player has specific items in their inventory. To check for inventory items, iterate over ActivePlayers and check HasItem or CountItem, returning true if any player satisfies the requirement. To support allowing town NPC to respawn without needing to meet the original respawn requirements, a feature added in Terraria v1.4.4, store a bool in a ModSystem and check it. ExamplePerson.CanTownNPCSpawn and TownNPCRespawnSystem.cs show an example of this. Returns false by default, preventing the town NPC from spawning. Called in single player or on the server only.
bool CheckConditions(int left, int right, int top, int bottom) hook same Allows you to define special conditions required for this town NPC's house. For example, Truffle requires the house to be in an aboveground mushroom biome. The left, right, top, and bottom parameters define the bounds of the room being checked. Methods like Housing_GetTestedRoomBounds and CountTileTypesInArea can facilitate implementing specific checks. Return false to prevent the npc from spawning due to failed condition checks. Called on the server and clients. The hint text explaining what a valid house is in the Housing button can be customized by adding the localization key Mods.YourModName.NPCs.YourNPCName.HousingText.HousingRequirements
List<string> SetNPCNameList() hook same Allows you to give a list of names this NPC can be given on spawn. By default, returns a blank list, which means the NPC will simply use its type name as its given name when prompted.
bool CanChat() hook same Allows you to determine whether this NPC can talk with the player. By default, returns if the NPC is a town NPC. This hook is not based on the type of the NPC, and is queried specifically on the ModNPC itself, regardless of if, for example, the type of the NPC instance is changed. Returning true in all circumstances will always make the NPC able to be chatted with no matter what else you do the NPC instance itself. Called on the local client only.
string GetChat() hook same Allows you to give this NPC a chat message when a player talks to it. By default returns something embarrassing. Called on the local client only.
void RegisterChatButtons(NPCInteractionList interactions) hook same Allows you to register chat buttons for this NPC. Use interactions to register new buttons. The "Close", "Happiness", and "Housing" buttons will automatically be registered before the buttons registered here. An NPC can only have 32 chat buttons shown at one time.
void OnChatButtonClicked(NPCInteraction interaction) hook same Allows you to make something happen whenever a button is clicked on this NPC's chat window. Called on the local client only.
void SetChatButtons(ref string button, ref string button2) hook only here The text of the two chat buttons. For more buttons use RegisterChatButtons.
void OnChatButtonClicked(bool firstButton, ref string shopName) hook differs Allows you to make something happen whenever a button is clicked on this NPC's chat window. Called on the local client only. tML: void OnChatButtonClicked(NPCInteraction interaction)
void AddShops() hook same Allows you to add shops to this NPC, similar to adding recipes for items. Make a new NPCShop, and items to it, and call Register
void ModifyActiveShop(string shopName, Item[] items) hook same Allows you to modify the contents of a shop whenever player opens it. To create a shop, use AddShops Note that for special shops like travelling merchant, the shopName may not correspond to a NPCShop in the NPCShopDatabase Also note that unused slots in items are null while IsAir entries are entries that have a reserved slot (SlotReserved) but did not have their conditions met. These should not be overwritten. Called on the local client only.
void ModifyNPCHappiness(int primaryPlayerBiome, ShopHelper shopHelperInstance, bool[] nearbyNPCsByType) hook only here Changes how the NPC feels about a biome or a neighbour. Phone: Runs when the game works out the shop price, and primaryPlayerBiome is always 0. In tModLoader the call is commented out.
void TownNPCAttackStrength(ref int damage, ref float knockback) hook same Allows you to determine the damage and knockback of this town NPC's attack before the damage is scaled. (More information on scaling in GlobalNPC.BuffTownNPCs.) Called on the server and clients.
void TownNPCAttackCooldown(ref int cooldown, ref int randExtraCooldown) hook same Allows you to determine the cooldown between each of this town NPC's attack. The cooldown will be a number greater than or equal to the first parameter, and less then the sum of the two parameters. Called on the server and clients.
void TownNPCAttackProj(ref int projType, ref int attackDelay) hook same Allows you to determine the projectile type of this town NPC's attack, and how long it takes for the projectile to actually appear. This hook is only used when the town NPC has an attack type (AttackType) of 0 (throwing), 1 (shooting), or 2 (magic). Called on the server and clients.
void TownNPCAttackProjSpeed(ref float multiplier, ref float gravityCorrection, ref float randomOffset) hook same Allows you to determine the speed at which this town NPC throws a projectile when it attacks. Multiplier is the speed of the projectile, gravityCorrection is how much extra the projectile gets thrown upwards, and randomOffset allows you to randomize the projectile's velocity in a square centered around the original velocity. This hook is only used when the town NPC has an attack type (AttackType) of 0 (throwing), 1 (shooting), or 2 (magic). Called on the server and clients.
void TownNPCAttackShoot(ref bool inBetweenShots) hook same Allows you to tell the game that this town NPC has already created a projectile and will still create more projectiles as part of a single attack so that the game can animate the NPC's attack properly. Only used when the town NPC has an attack type (AttackType) of 1 (shooting). Called on the server and clients.
void TownNPCAttackMagic(ref float auraLightMultiplier) hook same Allows you to control the brightness of the light emitted by this town NPC's aura when it performs a magic attack. Only used when the town NPC has an attack type (AttackType) of 2 (magic) Called on the server and clients.
void TownNPCAttackSwing(ref int itemWidth, ref int itemHeight) hook same Allows you to determine the width and height of the item this town NPC swings when it attacks, which controls the range of this NPC's swung weapon. Only used when the town NPC has an attack type (AttackType) of 3 (swinging). Called on the server and clients.
void DrawTownAttackGun(ref Texture2D item, ref Rectangle itemFrame, ref float scale, ref int horizontalHoldoutOffset) hook same Allows you to customize how this town NPC's weapon is drawn when this NPC is shooting (this NPC must have an attack type (AttackType) of 1). scale is a multiplier for the item's drawing size, item is the Texture2D instance of the item to be drawn, itemFrame is the section of the texture to draw, and horizontalHoldoutOffset is how far away the item should be drawn from the NPC. To use an actual item sprite, use Main.GetItemDrawFrame(itemTypeHere, out item, out itemFrame); horizontalHoldoutOffset = (int)Main.DrawPlayerItemPos(1f, itemType).X - someOffsetHere Called on all clients.
void DrawTownAttackSwing(ref Texture2D item, ref Rectangle itemFrame, ref int itemSize, ref float scale, ref Vector2 offset) hook same Allows you to customize how this town NPC's weapon is drawn when this NPC is swinging it (this NPC must have an attack type (AttackType) of 3). item is the Texture2D instance of the item to be drawn, itemFrame is the section of the texture to draw, itemSize is the width and height of the item's hitbox (the same values for TownNPCAttackSwing), scale is the multiplier for the item's drawing size, and offset is the offset from which to draw the item from its normal position. The item texture can be any texture, but if it is an item texture you can use GetItemDrawFrame to set item and itemFrame easily. Called on all clients.

NPC

struct Terraria.NPC : IEntityWithGlobals<GlobalNPC>

What Bunny Loader adds to the game's NPC.

Member Kind tModLoader What it does
IEntitySource GetSource_FromThis(string context) method only here The source for what this NPC creates.
IEntitySource GetSource_Loot(string context) method same The source for what it drops.
IEntitySource GetSource_Death(string context) method only here The source for what it creates at death.
IEntitySource GetSource_FromAI(string context) method same The source for what its AI creates.
IEntitySource GetSource_GiftOrReward(string context) method only here The source for what it gives the player.
int GetPartyHatGore() method same Returns the gore type of the party hat this NPC is currently wearing. If the NPC isn't wearing a party hat, 0 is returned.
NPC NewNPCDirect(IEntitySource source, int x, int y, int type, int start, float ai0, float ai1, float ai2, float ai3, int target) static method same This particular overload returns the actual NPC instance rather than the index of the spawned NPC within the npc array. A short-hand for Main.npc[NPC.NewNPC(...)]
NPC NewNPCDirect(IEntitySource source, Vector2 position, int type, int start, float ai0, float ai1, float ai2, float ai3, int target) static method same This particular overload returns the actual NPC instance rather than the index of the spawned NPC within the npc array. It also uses a Vector2 for the spawn position instead of X and Y. A short-hand for Main.npc[NPC.NewNPC(...)]
void StrikeInstantKill() method same Kills it, synced in multiplayer.
int SimpleStrikeNPC(int damage, int hitDirection, bool crit, float knockBack, DamageClass damageType, bool damageVariation, float luck, bool noPlayerInteraction) method same Hits it with this damage.
ref MultipliableFloat GravityMultiplier property differs Multiply this value in order to change the NPCs active gravity, this can be done in AI as gravity values are reset slightly beforehand, and used slightly after. tML: MultipliableFloat GravityMultiplier
ref MultipliableFloat MaxFallSpeedMultiplier property differs Multiply this value in order to change the NPCs active maxFallSpeed, this can be done in AI as gravity values are reset slightly beforehand tML: MultipliableFloat MaxFallSpeedMultiplier
float[] GravityWetMultipliers static property same The effect of different liquids on NPC gravity. Provided for reference only, modifying these will have no effect. Corresponds with wet, lavaWet, honetWet, and shimmerWet.
float[] MaxFallSpeedWetMultipliers static property same The effect of different liquids on NPC maxFallSpeed. Provided for reference only, modifying these will have no effect. Corresponds with wet, lavaWet, honetWet, and shimmerWet.
bool CanBeChasedBy(object attacker, bool ignoreDontTakeDamage) method same Whether a homing projectile or minion may target it.
ModBossBar BossBar property differs Assign a special boss bar, vanilla or modded. Not used by vanilla. To assign a modded boss bar, use NPC.BossBar = ModContent.GetInstance(); where ExampleBossBar is a ModBossBar To assign a vanilla boss bar for whatever reason, fetch it first through the NPC type using Main.BigBossProgressBar.TryGetSpecialVanillaBossBar tML: IBigProgressBar BossBar
void VanillaAI() method same Runs the game's AI for its aiStyle.
void HitEffect(int hitDirection, double dmg, bool instantKill) method differs Allows you to make things happen whenever this NPC is hit, such as creating dust or gores. Called on local, server, and remote clients. Usually when something happens when an NPC dies such as item spawning, you use NPCLoot, but you can use HitEffect paired with a check for if (NPC.life <= 0) to do client-side death effects, such as spawning dust, gore, or death sounds. tML: void HitEffect(int hitDirection, double dmg)
void HitEffect(int hitDirection, double dmg) method same Allows you to make things happen whenever this NPC is hit, such as creating dust or gores. Called on local, server, and remote clients. Usually when something happens when an NPC dies such as item spawning, you use NPCLoot, but you can use HitEffect paired with a check for if (NPC.life <= 0) to do client-side death effects, such as spawning dust, gore, or death sounds.
void HitEffect(HitInfo hit) method differs Allows you to make things happen whenever this NPC is hit, such as creating dust or gores. Called on local, server, and remote clients. Usually when something happens when an NPC dies such as item spawning, you use NPCLoot, but you can use HitEffect paired with a check for if (NPC.life <= 0) to do client-side death effects, such as spawning dust, gore, or death sounds. tML: void HitEffect(int hitDirection, double dmg)
void BecomeImmuneTo(int buffType) method same Adjusts buffImmune to make this NPC immune to the provided buff as well as all other buffs that inherit the immunity of that buff (via GrantImmunityWith). This method can be followed by ClearImmuneToBuffs if the NPC should clear any buff it currently has that it is now immune to.
void ClearImmuneToBuffs(out bool anyBuffsCleared) method same Clears all buffs on this NPC that the NPC is currently immune (buffImmune) to. The buff types and times will then be synced to clients. Use after manually changing buffImmune or using BecomeImmuneTo. anyBuffsCleared will be true if any buffs have been cleared by this method, it can be used to decide to spawn visual effects. Since this method should not be called on multiplayer clients, modders will need to manually sync any visual effects of this. This should not be called on multiplayer clients.
ModNPC ModNPC property same Its ModNPC, or null.
IReadOnlyList<GlobalNPC> EntityGlobals property differs Its GlobalNPC instances. tML: RefReadOnlyArray<GlobalNPC> EntityGlobals
T GetGlobalNPC<T>() method same Gets the instance of the specified GlobalNPC type. This will throw exceptions on failure.
T GetGlobalNPC<T>(T baseInstance) method same Gets the local instance of the type of the specified GlobalNPC instance. This will throw exceptions on failure.
bool TryGetGlobalNPC<T>(out T result) method same Gets the instance of the specified GlobalNPC type.
bool TryGetGlobalNPC<T>(T baseInstance, out T result) method same Safely attempts to get the local instance of the type of the specified GlobalNPC instance.
void CloneDefaults(int Type) method same Clones all the default stats (damage, health, defense, etc) of another NPC type. This should be used in SetDefaults prior to changing any other stats This is useful for creating a ModNPC that should be a copy of another NPC. Using CloneDefaults instead of manually setting stats will ensure that modifications done to the NPC being cloned by other mods will automatically apply to this clone as well. Note that for cloning negative NPCID, the final values might be very slightly off for higher difficulty modes due to the way difficulty scaling is applied.
void SetDefaults(int Type) method differs Allows you to set all your NPC's properties, such as width, damage, aiStyle, lifeMax, etc. tML: void SetDefaults(int Type, NPCSpawnParams spawnparams)
void SetDefaultsKeepPlayerInteraction(int Type) method same Changes its type and keeps who hit it.
void SetDefaultsKeepPlayerInteraction(int Type, NPCSpawnParams spawnParams) method same Changes its type and keeps who hit it.
NPCHappiness Happiness property same Provides access to (static) happiness data associated with this NPC's type.
string TownNPCName property only here A random name for a town NPC.

NPC.HitInfo

struct Terraria.NPC.HitInfo

Represents a finalized damage calculation for damage about to be applied to an NPC. This is the result of all modifications done previously in a HitModifiers provided to the ModifyHit hooks.

Member Kind tModLoader What it does
DamageClass DamageType field same The DamageType of the hit.
int SourceDamage property same The amount of damage 'dealt' to the NPC, before incoming damage multipliers, armor, critical strikes etc. Use this to trigger effects which scale based on damage dealt, and also deal damage. Cannot be set to less than 1. Using this instead of Damage can prevent diminishing returns from NPC defense, double crits, or excessively strong effects if the NPC has a vulnerability to the weapon/projectile (like vampires and stakes). Used by vanilla for dryad ward retaliation, and many sword on-hit projectiles like volcano and beekeeper
int Damage property same The amount of damage received by the NPC. How much life the NPC will lose. Is NOT capped at the NPC's current life. Will be 1 if InstantKill is set. Cannot be set to less than 1.
bool Crit field same Whether or not the hit is a crit
int HitDirection field same The direction to apply knockback in.
float Knockback field same The amount of knockback to apply. Should always be >= 0. Note that StrikeNPC has a staggered knockback falloff, and that critical strikes automatically get extra 40% knockback in excess of this value.
bool InstantKill field same If true, as much damage as necessary will be dealt, and damage number popups will not be shown for this hit. Has no effect if the NPC is immortal
bool HideCombatText field same If true, damage number popups will not be shown for this hit.
new HitInfo() constructor same Creates an instance.

NPC.HitModifiers

struct Terraria.NPC.HitModifiers

Represents a damage calculation in the process of being calculated for damage to be applied to an NPC. The final damage calculation will be present in the resulting HitInfo provided to the OnHit hooks.

Member Kind tModLoader What it does
DamageClass DamageType property same The DamageType of the hit.
int HitDirection property same The direction to apply knockback. If 0, no knockback will be applied. Could potentially be used for directional resistances. Can be overridden by HitDirectionOverride
bool SuperArmor property same If true, no amount of damage can get through the defense of this NPC, damage will be reduced to 1. CritDamage will still apply, but only Additive and Multiplicative. Maximum crit damage will be capped at 4.
StatModifier SourceDamage field same Use this to enhance or scale the base damage of the item/projectile/hit. This damage modifier will apply to SourceDamage and be transferred to on-hit effects. For effects which apply to all damage dealt by the player, or a specific damage type, consider using GetDamage instead. For effects which apply to all damage dealt by an item, consider using ModifyWeaponDamage instead. Used by vanilla for weapons with unique scaling such as jousting lance, ham bat, breaker blade. And for accessories which enhance a projectile (strong bees)
AddableFloat FlatBonusDamage field same Use this to add bonus damage to the hit, but not to on-hit effects. Used by vanilla for most summon tag damage.
AddableFloat ScalingBonusDamage field same Use this to add bonus Used by vanilla for melee parry buff (+4f) and some summon tag damage.
MultipliableFloat TargetDamageMultiplier field same Not recommended for modded use due to difficulty balancing around defense, consider multiplying FinalDamage instead. Used by vanilla for banners, cultist projectile resistances, extra damage for stakes against vampires etc.
StatModifier Defense field same The defense of the receiver, including any temporary modifiers (buffs/debuffs). Increase Base to add extra defense. Add for scaling buffs (eg +0.1f for +10% defense). Multiply for debuffs (eg *0.9f for -10% defense). Decrease Flat to provide flat debuffs like ichor or betsys curse
AddableFloat ArmorPenetration field same Flat defense reduction. Applies after ScalingArmorPenetration. Add to give bonus flat armor penetration. Do not subtract or multiply, consider altering Defense or ScalingArmorPenetration instead. Used by the ArmorPenetration, ArmorPenetration and GetTotalArmorPenetration stats.
AddableFloat ScalingArmorPenetration field same Used to ignore a fraction of enemy armor. Applies before flat ArmorPenetration. Recommend only additive buffs, no multiplication or subtraction. At 1f, the attack will completely ignore all defense.
MultipliableFloat DefenseEffectiveness field same The conversion ratio between defense and damage reduction. Defaults to 0.5 for NPCs. Depends on difficulty for players. Increase to make defense more effective and armor penetration more important. Recommend only multiplication, no addition or subtraction. Not recommended to for buffs/debuffs. Use for gamemode tweaks, or if an enemy revolves very heavily around armor penetration.
StatModifier CritDamage field same Applied to the final damage (after defense) result when the hit is a crit. Defaults to +1f additive (+100% damage). Add to give hits extra crit damage (eg +0.1f for 10% extra crit damage (total +110% or 2.1 times base). Add to Flat to give crits extra flat damage. Use with caution as this extra damage will not be reduced by armor. Multiplication not recommended for buffs. Could be used to decrease the effectiveness of crits on an enemy without disabling completely. Use of Base also not recommended.
StatModifier NonCritDamage field same Applied to damage after defense and before FinalDamage when the hit is not a crit. Effectively a compliment for CritDamage
StatModifier FinalDamage field same Applied to the final damage result. Used by takenDamageMultiplier to make enemies extra susceptible/resistant to damage. Multiply to make your enemy more susceptible or resistant to damage. Add to give 'bonus' post-mitigation damage. Add to Base to deal damage which ignores armor, but still respects scaling damage reductions or increases. Adding to Flat will ignore all reductions or increases to deal unconditional damage. Not recommended due to potential compatibility issues with enemy or player damage reduction effects, use Base instead.
MultipliableFloat DamageVariationScale field same Multiply to adjust the damage variation of the hit. Multiply by 0 to disable damage variation. Default damage variation is 15%, so maximum scale is ~6.67 Only affects hits where damage variation is enabled (which is most projectile/item/NPC damage)
void SetMaxDamage(int limit) method same Sets an inclusive upper bound on the final damage of the hit. Can be set by multiple mods, in which case the lowest limit will be used. Cannot be set to less than 1
void DisableCrit() method same Disables CritDamage calculations, and clears Crit flag from the resulting hit.
void SetCrit() method same Sets the hit to be a crit. Does nothing if DisableCrit has been called
void DisableKnockback() method same Sets the hit to have no knockback, regardless of Knockback values. Set automatically for NPC with knockBackResist values of 0 for consistency.
StatModifier Knockback field same Used by onFire2 buff (additive) and knockBackResist (multiplicative) Recommend using ModifyWeaponKnockback or GetKnockback instead where possible. Add for knockback buffs. Multiply for knockback resistances. Subtraction not recommended. Knockback falloff still applies after this, so high knockback has diminishing returns.
int HitDirectionOverride property same Overrides the direction to apply knockback. Will not affect HitDirection, only the final HitDirection If set by multiple mods, only the last override will apply. Intended for use by flails, or other projectiles which need to hit the NPC away from the player, even when striking from behind.
void SetInstantKill() method same Set to make the hit instantly kill the target, dealing as much damage as necessary. Combat text will not be shown.
void HideCombatText() method same Set to hide the damage number popup for this hit.
HitInfoModifier ModifyHitInfo event same Use with caution and consider other alternatives first. Can be used to register a callback to freely modify the HitInfo produced by ToHitInfo before it is returned If multiple mods register different callbacks which modify the hit info in different ways the results could be a mess!
new HitModifiers() constructor same Creates an instance.
int GetDamage(float baseDamage, bool crit, bool damageVariation, float luck) method same The final damage of the hit.
float GetKnockback(float baseKnockback) method same The final knockback of the hit.
HitInfo ToHitInfo(float baseDamage, bool crit, float baseKnockback, bool damageVariation, float luck) method same The hit as a HitInfo.

NPC.Spawner

struct Terraria.NPC.Spawner

Spawns a boss or event the way the game does, through the phone's NPC.Spawner.

Member Kind tModLoader What it does
int SpawnTileX property same The x-coordinate of the tile the NPC will spawn above.
int SpawnTileY property same The y-coordinate of the tile the NPC will spawn above.
int GroundTileY property same The y-coordinate of the tile used for some spawning logic pertaining to tiles. This is potentially below SpawnTileY if that tile (and potentially some number of tiles below it) happens to be a platform, conveyor belt, or any other tile that is not considered valid for spawning logic purposes.
int SpawnTileType property same The tile type (TileID or ) at SpawnTileX and GroundTileY.
int SpawnWallType property same The wall type (WallID or ) at SpawnTileX and GroundTileY.
Player Player property same The player that this NPC is spawning around. Note that there are many fields in Spawner like ZoneJungle that appear to be duplicates of Player fields, such as ZoneJungle, but you should always used the Spawner fields if present for NPC spawning logic to properly account for custom NPC spawning logic. For example, the dual dungeons secret world seed affects those fields for custom spawning logic separately from the logic used for the Player fields, which would affect visuals and other things.
bool SafeRangeX property same Whether or not the NPC is horizontally within the range near the player in which NPCs cannot spawn. If this is true, it also means that it is vertically outside of the range near the player in which NPCs cannot spawn.

NPCAIStyleID

class Terraria.ID.NPCAIStyleID

Values of NPC.aiStyle.

Members: Search, FaceClosestPlayer, Slime, DemonEye, Fighter, EyeOfCthulhu, Flying, Worm, Passive, Caster, Spell, CursedSkull, SkeletronHead, SkeletronHand, ManEater, Bat, KingSlime, Piranha, Vulture, Jellyfish, Antlion, SpikeBall, BlazingWheel, HoveringFighter, EnchantedSword, Bird, Mimic, Unicorn, WallOfFleshMouth, WallOfFleshEye, TheHungry, Retinazer, Spaazmatism, SkeletronPrimeHead, PrimeSaw, PrimeVice, PrimeCannon, PrimeLaser, TheDestroyer, Snowman, GiantTortoise, Spider, Herpling, LostGirl, QueenBee, FlyingFish, GolemBody, GolemHead, GolemFist, FreeGolemHead, AngryNimbus, Spore, Plantera, PlanteraHook, PlanteraTentacle, BrainOfCthulhu, Creeper, DungeonSpirit, MourningWood, Pumpking, PumpkingScythe, IceQueen, SantaNK1, ElfCopter, Flocko, Firefly, Butterfly, CritterWorm, Snail, Duck, DukeFishron, DukeFishronBubble, Sharkron, BubbleShield, TeslaTurret, Corite, Rider, MartianSaucer, MoonLordCore, MoonLordHand, MoonLordHead, MartianProbe, TrueEyeOfCthulhu, MoonLeachClot, LunaticDevote, LunaticCultist, StarCell, AncientVision, BiomeMimic, Mothron, MothronEgg, BabyMothron, GraniteElemental, TargetDummy, FlyingDutchman, CelestialPillar, SmallStarCell, FlowInvader, NebulaFloater, Unused0, SolarFragment, AncientLight, AncientDoom, SandElemental, SandShark, Unknown1, DD2EterniaCrystal, DD2MysteriousPortal, DD2Fighter, DD2Flying, DD2DarkMage, DD2Betsy, DD2LightningBug, Fairy, Balloon, Dragonfly, Ladybug, WaterStrider, Dreadnautilus, Seahorse, AngryDandelion, EmpressOfLight, QueenSlime, PiratesCurse

NPCDefinition

class Terraria.ModLoader.Config.NPCDefinition : EntityDefinition

NPCDefinition represents an NPC identity.

Member Kind tModLoader What it does
Func<TagCompound, NPCDefinition> DESERIALIZER static field same Rebuilds this value from a TagCompound.
bool IsUnloaded override same Whether its mod is off.
int Type override same The NPCID of the NPC this NPCDefinition represents. Will be -66 (NegativeIDCount) for IsUnloaded NPCDefinition.
new NPCDefinition() constructor same Creates an instance.
new NPCDefinition(int type) constructor same Note: As ModConfig loads before other content, make sure to only use NPCDefinition for modded content in ModConfig classes.
new NPCDefinition(string key) constructor same Creates an instance.
new NPCDefinition(string mod, string name) constructor same Creates an instance.
NPCDefinition FromString(string s) static method same Builds this value from its text form.
NPCDefinition Load(TagCompound tag) static method same Rebuilds the definition from a tag.
string DisplayName override same The name shown to the player, as localized text.

NPCHappiness

struct Terraria.ModLoader.NPCHappiness

This struct provides access to an NPC type's NPC & Biome relationships.

Member Kind tModLoader What it does
int NpcType field same The NPC.
NPCHappiness Get(int npcType) static method same The happiness of an NPC.
NPCHappiness SetNPCAffection<T>(AffectionLevel affectionLevel) method same How much it likes a neighbour.
NPCHappiness SetNPCAffection(int npcId, AffectionLevel affectionLevel) method same How much it likes a neighbour.
NPCHappiness SetBiomeAffection<T>(AffectionLevel affectionLevel) method same How much it likes a biome.
NPCHappiness SetBiomeAffection(ModBiome biome, AffectionLevel affectionLevel) method differs How much it likes a biome. tML: NPCHappiness SetBiomeAffection<T>(AffectionLevel affectionLevel)
NPCHappiness SetBiomeAffection(AShoppingBiome biome, AffectionLevel affectionLevel) method differs How much it likes a biome. tML: NPCHappiness SetBiomeAffection<T>(AffectionLevel affectionLevel)
Dictionary<AffectionLevel, float> AffectionLevelToPriceMultiplier static field not here Allows you to modify the shop price multipliers associated with a (biome/npc type) relationship level.

NPCHeadLoader

static class Terraria.ModLoader.NPCHeadLoader

This class serves as a central place from which NPC head slots are stored and NPC head textures are assigned. This can be used to obtain the corresponding slots to head textures.

Member Kind tModLoader What it does
int GetHeadSlot(string texture) static method same Gets the index of the head texture corresponding to the given texture path.
int GetNPCHeadSlot(int type) static method only here The default head slot of an NPC, or -1.
int VanillaHeadCount static field not here The number of vanilla town NPC head textures that exist.
int VanillaBossHeadCount static field not here The number of vanilla boss head textures that exist.
int NPCHeadCount static property not here Internal here.
int GetBossHeadSlot(string texture) static method not here Gets the index of the boss head texture corresponding to the given texture path.

NPCID

struct Terraria.ID.NPCID

NPC types. A mod NPC's type comes from ModContent.NPCType<T>().

Member Kind tModLoader What it does

NPCID.BestiaryDrawOffsets

class Terraria.ID.NPCID.BestiaryDrawOffsets · only in Bunny Loader

NPCID.Sets.NPCBestiaryDrawOffset: how an NPC is drawn in the bestiary.

Member Kind tModLoader What it does
bool ContainsKey(int npcNetId) method only here Whether there is an entry for this key.
bool TryGetValue(int npcNetId, out NPCBestiaryDrawModifiers value) method only here Reads an entry if there is one.
NPCBestiaryDrawModifiers this[int npcNetId] indexer only here Reads or writes one entry.
void Add(int npcNetId, NPCBestiaryDrawModifiers value) method same Sets how an NPC draws in the bestiary.
bool Remove(int npcNetId) method only here Removes an entry.

NPCID.PortraitOffsetTable

class Terraria.ID.NPCID.PortraitOffsetTable · only in Bunny Loader

NPCID.Sets.NPCPortraitsCloseUpOffsets: the position of a portrait in chat.

Member Kind tModLoader What it does
bool ContainsKey(int npcNetId) method only here Whether there is an entry for this key.
bool TryGetValue(int npcNetId, out Vector2 value) method only here Reads an entry if there is one.
Vector2 this[int npcNetId] indexer only here Reads or writes one entry.
void Add(int npcNetId, Vector2 value) method same Sets a portrait's position.
bool Remove(int npcNetId) method only here Removes an entry.

NPCID.PortraitTable

class Terraria.ID.NPCID.PortraitTable · only in Bunny Loader

NPCID.Sets.NPCPortraits: the portrait shown in chat, per NPC.

Member Kind tModLoader What it does
bool ContainsKey(int npcNetId) method only here Whether there is an entry for this key.
bool TryGetValue(int npcNetId, out NPCPortraitProvider value) method only here Reads an entry if there is one.
NPCPortraitProvider this[int npcNetId] indexer only here Reads or writes one entry.
void Add(int npcNetId, NPCPortraitProvider value) method same Sets an NPC's portrait.
bool Remove(int npcNetId) method only here Removes an entry.

NPCID.Sets

static class Terraria.ID.NPCID.Sets

Tables indexed by NPC type.

Member Kind tModLoader What it does
BestiaryDrawOffsets NPCBestiaryDrawOffset static property differs How each NPC draws in the bestiary. tML: Dictionary<int, NPCBestiaryDrawModifiers> NPCBestiaryDrawOffset
PortraitTable NPCPortraits static property differs The portrait of each NPC. tML: Dictionary<int, NPCPortraitProvider> NPCPortraits
PortraitOffsetTable NPCPortraitsCloseUpOffsets static property differs The close-up portrait's position per NPC. tML: Dictionary<int, Vector2> NPCPortraitsCloseUpOffsets
PortraitOffsetTable NPCPortraitsFullBodyRetroOffsets static property differs The full body portrait's position per NPC. tML: Dictionary<int, Vector2> NPCPortraitsFullBodyRetroOffsets
BasicNPCPortrait BasicPortrait(string texturePath) static method same A portrait from one texture.
bool[] NeverDropsResourcePickups static property same NPC in this set do not drop resource pickups, such as hearts or star items. Vanilla entries in this set include MotherSlime, CorruptSlime, and Slimer, all of which spawn other NPC when killed, suggesting that they split apart rather than died, hinting at why they shouldn't drop resource pickups. Defaults to false.
bool[] CannotDropSouls static property same Whether or not a given NPC is excluded from dropping hardmode souls (Soul of Night/Light) Contains vanilla NPCs that are easy to spawn in large numbers, preventing easy soul farming Do not add your NPC to this if it would be excluded automatically (i.e. critter, town NPC, or no coin drops)
bool[] ActsLikeTownNPC static property same Whether or not a given NPC will act like a town NPC in terms of AI, animations, and attacks, but not in other regards, such as appearing on the minimap, like the bone merchant in vanilla. Phone: Set in SetStaticDefaults. Holds in the AI, in talking and in the walking frames.
bool[] NoTownNPCHappiness static property same If true, the given NPC will not count towards town NPC happiness and won't have a happiness button. Pets (IsTownPet) do not need to set this.
bool[] SpawnsWithCustomName static property same Whether or not a given NPC will spawn with a custom name like a town NPC. In order to determine what name will be selected, override the TownNPCName hook. True will force a name to be rolled regardless of vanilla behavior. False will have vanilla handle the naming.
bool[] CannotSitOnFurniture static property same Whether or not a given NPC can sit on suitable furniture (CanBeSatOnForNPCs)
bool[] IsPetSmallForPetting static property same While petting, the player's arm will be angled up by default. If the NPC is in this set, the player's armor will be angled down instead. Defaults to false.
int[] PlayerDistanceWhilePetting static property same While petting, the number of pixels away the player stands from the NPC. Defaults to 36 pixels.
ref bool[] ImmuneToWhipTags static property differs If true, this NPC type (type) will be immune to all whip "tag" effects and "tag" buffs. Use this for special NPCs that cannot be hit at all, such as fairy critters, container NPCs like Martian Saucer and Pirate Ship, bound town slimes, and Blazing Wheel. Dungeon Guardian also is in this set to prevent the bonus damage from "tag" effects and "tag" buffs. If the NPC should be attacked, it is recommended to set ImmuneToRegularBuffs to true instead. This will prevent all debuffs except "tag" effects and debuffs (WhipTagEffect and IsATagBuff), which are intended to affect enemies typically seen as immune to all debuffs. Tag effects and tag debuffs are special debuffs that facilitate combat mechanics, they are not something that adversely affects NPC. Modders can specify specific buffs to be vulnerable to by assigning SpecificDebuffImmunity to false. tML: bool[] ImmuneToWhipTags
ref bool[] ImmuneToRegularBuffs static property differs If true, this NPC type (type) will be immune to all debuffs except tag effects and debuffs (WhipTagEffect and IsATagBuff) by default. Use this for NPCs that can be attacked that should be immune to all normal debuffs. Tag effects and tag debuffs are special effects that facilitate combat mechanics, such as the "summon tag damage" applied by whip weapons. Wraith, Reaper, Lunatic Cultist, the Celestial Pillars, The Destroyer, and the Martian Saucer Turret/Cannon/Core are examples of NPCs that use this setting. Modders can specify specific buffs to be vulnerable to by assigning SpecificDebuffImmunity to false. tML: bool[] ImmuneToRegularBuffs
ref bool[][] SpecificDebuffImmunity static property differs Indexed by NPC type and then Buff type. If true, this NPC type (type) will be immune (buffImmune) to the specified buff type. If false, the NPC will not be immune. By default, NPCs aren't immune to any buffs, but ImmuneToRegularBuffs can make an NPC immune to all buffs except "tag" effects and "tag" buffs. ImmuneToWhipTags can make an NPC immune to all "tag" effects and "tag" buffs. The values in this set override those settings. Additionally, the effects of GrantImmunityWith will also be applied. Inherited buff immunities do not need to be specifically assigned, as they will be automatically applied. Setting an inherited debuff to false in this set can be used to undo the effects of GrantImmunityWith, if needed. Defaults to null, indicating no immunity override. tML: bool[][] SpecificDebuffImmunity
bool[] IsTownChild static field not here If true, the given Town NPC won't drop a tombstone on death in hardcore mode and will have the "NPC has left!" death message unless specified otherwise by DeathMessage. This does NOT affect the gore spawned when the NPC dies. Defaults to false.
bool[] AllowDoorInteraction static field not here Whether or not this NPC can still interact with doors if they use the Vanilla TownNPC aiStyle (AKA aiStyle == 7) but are not actually marked as Town NPCs (AKA npc.townNPC == true).
bool[] BelongsToInvasionGoblinArmy static field not here If true for a given NPC type (type), then that NPC belongs to the Goblin Army invasion. During the Goblin Army invasion, NPCs in this set will decrement invasionSize by the amount specified in InvasionSlotCount when killed. If any NPC in this set is alive, the Goblin Army music will play. Defaults to false.
bool[] BelongsToInvasionFrostLegion static field not here If true for a given NPC type (type), then that NPC belongs to the Frost Legion invasion. During the Frost Legion invasion, NPCs in this set will decrement invasionSize by the amount specified in InvasionSlotCount when killed. If any NPC in this set is alive, the Boss 3 music will play. Defaults to false.
bool[] BelongsToInvasionPirate static field not here If true for a given NPC type (type), then that NPC belongs to the Pirate invasion. During the Pirate invasion, NPCs in this set will decrement invasionSize by the amount specified in InvasionSlotCount when killed. If any NPC in this set is alive, the Pirate Invasion music will play. Defaults to false.
bool[] BelongsToInvasionMartianMadness static field not here If true for a given NPC type (type), then that NPC belongs to the Martian Madness invasion. During the Martian Madness invasion, NPCs in this set will decrement invasionSize by the amount specified in InvasionSlotCount when killed. If any NPC in this set is alive, the Martian Madness music will play. Defaults to false.
bool[] NoInvasionMusic static field not here If true for a given NPC type (type), then that NPC will not play its associated invasion music. By default, alive NPCs in any BelongsToInvasion set will automatically play the associated invasion music. Defaults to false.
int[] InvasionSlotCount static field not here If above 0 for a given NPC type (type), and its associated invasion is NOT a wave-based one, then that NPC will decrement invasionSize by that amount when killed.
bool[] DoesntDespawnToInactivityAndCountsNPCSlots static field not here This NPC will not despawn due to being far offscreen, but will still count towards nearbyActiveNPCs. Unlike returning false in CheckActive, this NPC still counts towards spawn limits.

NPCID.Sets.NPCBestiaryDrawModifiers

struct Terraria.ID.NPCID.Sets.NPCBestiaryDrawModifiers

How to draw an NPC in the bestiary: position, velocity, scale, frame.

Member Kind tModLoader What it does
new NPCBestiaryDrawModifiers() constructor same Creates an instance.

NPCInteraction

abstract class Terraria.GameContent.NPCInteraction

A button of a town NPC's chat. Add yours with ModNPC.RegisterChatButtons or GlobalNPC.RegisterChatButtons.

Member Kind tModLoader What it does
Player LocalPlayer property same The player in the chat.
NPC TalkNPC property same The NPC in the chat.
int TalkNPCType property same That NPC's type.
bool ShowExclamation hook same Whether the button shows a !.
bool Condition() hook same Whether the button shows now.
string GetText() hook same The button's text.
void Interact() hook same Runs when it is tapped.
bool TryAddCoins(ref Color textColor, out int coins) hook same Shows a price beside the text.
void TextColor(ref Color normal, ref Color mouseOver, bool hovering) hook same The text's colors.

NPCInteractionDatabase

class Terraria.ModLoader.NPCInteractionDatabase

This holds and registers the NPCInteractionList data for each NPC. The Close, Happiness, Housing, and Pet buttons are already predefined and can be used with CloseButton, etc.

Member Kind tModLoader What it does
NPCInteraction CloseButton static field same Predefined Close button for NPC chat buttons.
NPCInteraction HappinessButton static field same Predefined Happiness button for NPC chat buttons.
NPCInteraction HousingButton static field same Predefined Housing button for NPC chat buttons.
NPCInteraction PetButton static field same Predefined Pet button for NPC chat buttons.
NPCInteractionList GetInteractionList(int type) method not here Returns the NPCInteractionList of the NPC.
IReadOnlyList<Entry> GetInteractionEntries(int type) method not here Returns the full List<NPCInteractionList.Entry> of the NPC.

NPCInteractionDatabase.DedicatedButton

class Terraria.ModLoader.NPCInteractionDatabase.DedicatedButton : NPCInteraction · only in Bunny Loader

A chat button with a fixed place: Close, Happiness, Housing.

Member Kind tModLoader What it does
bool Condition() override only here Whether the button shows.
string GetText() override only here The button's text.
void Interact() override only here Runs when it is tapped.

NPCInteractionList

class Terraria.ModLoader.NPCInteractionList

Allows for NPCInteraction chat buttons to be assigned to an NPC.

Member Kind tModLoader What it does
int Type property same The NPC this list belongs to.
IEnumerable<NPCInteraction> Interactions property same All of the NPCInteractions for the NPC.
IReadOnlyList<Entry> Entries property same All of the entries for this NPC which includes the NPCInteraction and if it is Enabled.
Entry Prepend(NPCInteraction interaction) method same Registers a button at the beginning of the list.
Entry Append(NPCInteraction interaction) method same Registers a button at the end of the list (after Happiness and Housing buttons if applicable).
Entry InsertAfter(NPCInteraction interactionToRegister, NPCInteraction interactionAfter) method same Adds a button after another one.
Entry InsertAfter(NPCInteraction interactionToRegister, Entry interactionAfter) method same Adds a button after another one.
Entry InsertBefore(NPCInteraction interactionToRegister, NPCInteraction interactionBefore) method same Adds a button before another one.
Entry InsertBefore(NPCInteraction interactionToRegister, Entry interactionBefore) method same Adds a button before another one.
void Disable(Entry interaction) method same Disables an interaction for the current NPC. The interaction needs to be the exact instance of the button. The Close, Happiness, Housing, and Pet buttons are already predefined and can be used with CloseButton, etc. If you don't already have the instance, use Disable or search for the instance first.
void Disable(NPCInteraction interaction) method same Disables an interaction for the current NPC. The interaction needs to be the exact instance of the button. The Close, Happiness, Housing, and Pet buttons are already predefined and can be used with CloseButton, etc. This method will find the first NPCInteraction by instance that matches and mark it as disabled.
bool IsEnabled(Entry interaction) method same If the interaction is enabled. Defaults to true.
bool IsEnabled(NPCInteraction interaction) method same If the interaction is enabled. Defaults to true.

NPCInteractionList.Entry

class Terraria.ModLoader.NPCInteractionList.Entry

This contains the NPCInteraction as well as if the interaction is enabled.

Member Kind tModLoader What it does
NPCInteraction NPCInteraction property same The stored NPCInteraction.
bool Enabled property same If the interaction is enabled. Use interactions.Disable(interaction) to disable. Defaults to true.
string ToString() override same The text form of this value.

NPCInteractions

static class Terraria.GameContent.NPCInteractions

Ready-made chat buttons.

Member Kind tModLoader What it does
NPCInteraction Shop(string shopName, string customTextKey) static method same A button that opens a shop by name.

NPCInteractions.Actions

static class Terraria.GameContent.NPCInteractions.Actions

The game's chat buttons as NPCInteraction objects.

Member Kind tModLoader What it does

NPCInteractions.Actions.CloseChat

class Terraria.GameContent.NPCInteractions.Actions.CloseChat : DedicatedButton

The Close button.

Member Kind tModLoader What it does
new CloseChat() constructor same Creates an instance.

NPCInteractions.Actions.GuideReverseCrafting

class Terraria.GameContent.NPCInteractions.Actions.GuideReverseCrafting : VanillaOption(false)

The Guide's crafting button.

Member Kind tModLoader What it does

NPCInteractions.Actions.GuideTip

class Terraria.GameContent.NPCInteractions.Actions.GuideTip : VanillaOption(true)

The Guide's help button.

Member Kind tModLoader What it does

NPCInteractions.Actions.OpenShop

class Terraria.GameContent.NPCInteractions.Actions.OpenShop : NPCInteraction

A button that opens a shop by name.

Member Kind tModLoader What it does
bool Condition() override same Whether the button shows.
string GetText() override same The shop button's text.
void Interact() override same Opens the shop.

NPCInteractions.Actions.VanillaOption

abstract class Terraria.GameContent.NPCInteractions.Actions.VanillaOption : NPCInteraction · only in Bunny Loader

One of the two buttons the game gives an NPC.

Member Kind tModLoader What it does
bool First property only here Whether this is the first button of the two.
bool Condition() override same Whether the game shows this button for the NPC.
string GetText() override only here The text the game gives the button.
void Interact() override only here Runs what the game does for the button.

NPCLoader

static class Terraria.ModLoader.NPCLoader

This serves as the central class from which NPC-related functions are carried out. It also stores a list of mod NPCs by ID.

Member Kind tModLoader What it does
void SetBestiary(NPC npc, BestiaryDatabase database, BestiaryEntry bestiaryEntry) static method same Allows you to set an NPC's information in the Bestiary.
HashSet<int> blockLoot static field differs Allows you to stop an NPC from dropping specific loot by adding item IDs to this list. This list will be cleared whenever NPCLoot ends. Useful for dynamically removing an item in the NPC's loot table. To remove an item drop use the PreKill hook to add the item's ID to this list. Editing the drop rules themselves is usually the better and more compatible approach, however. tML: IList<int> blockLoot
bool CanHitPlayer(NPC npc, Player target, ref int cooldownSlot) static method same Allows you to determine whether this NPC can hit the given player. Return false to block this NPC from hitting the target. Returns true by default. CooldownSlot determines which of the player's cooldown counters (ImmunityCooldownID) to use, and defaults to -1 (General). Called on the local client only.
void ModifyHitPlayer(NPC npc, Player target, ref HurtModifiers modifiers) static method same Allows you to modify the damage, etc., that this NPC does to a player. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. The final hit values such as the final damage can only be retrieved from the HurtInfo in the OnHitPlayer hook. Called on the local client only.
void OnHitPlayer(NPC npc, Player target, HurtInfo hurtInfo) static method same Allows you to create special effects when this NPC hits a player (for example, inflicting debuffs). Changes to the hit such as the damage must be done by modifying the HurtModifiers properties in the ModifyHitPlayer hook. Called on the local client only.
bool CanHitNPC(NPC npc, NPC target) static method same Allows you to determine whether this NPC can hit the given friendly NPC. Return false to block the NPC from hitting the target, and return true to use the vanilla code for whether the target can be hit. Returns true by default. Called in single player or on the server only.
void ModifyHitNPC(NPC npc, NPC target, ref HitModifiers modifiers) static method same Allows you to modify the damage, knockback, etc., that this NPC does to a friendly NPC. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. The final hit values such as the final damage can only be retrieved from the HitInfo in the OnHitNPC hook. Called in single player or on the server only.
void OnHitNPC(NPC npc, NPC target, in HitInfo hit) static method same Allows you to create special effects when this NPC hits a friendly NPC. Changes to the hit such as the damage must be done by modifying the HitModifiers properties in the ModifyHitNPC hook. Called in single player or on the server only.
int NPCCount static property same How many exist, with the game's and every mod's.
ModNPC GetNPC(int type) static method same Gets the ModNPC template instance corresponding to the specified type (not the clone/new instance which gets added to NPCs as the game is played).
void BossHeadSlot(NPC npc, ref int index) static method same Allows you to customize the boss head texture used by an NPC based on its state. Set index to -1 to stop the texture from being displayed. Called on all clients.
void BossHeadRotation(NPC npc, ref float rotation) static method same Allows you to customize the rotation of this NPC's boss head icon on the map. Called on all clients.
void BossHeadSpriteEffects(NPC npc, ref SpriteEffects spriteEffects) static method same Allows you to flip this NPC's boss head icon on the map. Called on all clients.
Color GetAlpha(NPC npc, Color lightColor) static method same Allows you to determine the color and transparency in which this NPC is drawn. Return null to use the default color (normally light and buff color). Returns null by default. Called on all clients.
void DrawEffects(NPC npc, ref Color drawColor) static method same Allows you to add special visual effects to this NPC (such as creating dust), and modify the color in which the NPC is drawn. Called on all clients.
bool PreDraw(NPC npc, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) static method same Allows you to draw things behind this NPC, or to modify the way this NPC is drawn. Substract screenPos from the draw position before drawing. Return false to stop the game from drawing the NPC (useful if you're manually drawing the NPC). Returns true by default. Called on all clients.
void PostDraw(NPC npc, SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) static method same Allows you to draw things in front of this NPC. Substract screenPos from the draw position before drawing. This method is called even if PreDraw returns false. Called on all clients.
int PickEmote(NPC npc, Player closestPlayer, List<int> emoteList, WorldUIAnchor otherAnchor) static method same Allows you to change the emote that the NPC will pick Called in single player or on the server only.
void EmoteBubblePosition(NPC npc, ref Vector2 position, ref SpriteEffects spriteEffects) static method same Allows you to change the location and sprite direction of the emote bubble when anchored to an NPC. Called on all clients.
bool CanFallThroughPlatforms(NPC npc) static method same Allows you to determine how and when this NPC can fall through platforms and similar tiles. Return true to allow this NPC to fall through platforms, false to prevent it. Returns null by default, applying vanilla behaviors (based on aiStyle and type). Called on the server and clients.
bool ModifyCollisionData(NPC npc, Rectangle victimHitbox, ref int immunityCooldownSlot, ref float damageMultiplier, ref Rectangle npcHitbox) static method same Allows you to modify the NPC's , damage multiplier, and hitbox. Useful for implementing dynamic damage hitboxes that change in dimensions or deal extra damage. Returns false to prevent vanilla code from running. Returns true by default. Called on the server and clients.
bool SpecialOnKill(NPC npc) static method same Allows you to call OnKill on your own when the NPC dies, rather then letting vanilla call it on its own. Returns false by default. Called on the server and clients.
bool ModifyDeathMessage(NPC npc, ref NetworkText customText, ref Color color) static method same Allows you to modify the death message of a town NPC or boss (potentially derived from DeathMessage). This also affects what the dropped tombstone will say in the case of a town NPC. The text color can also be modified. When modifying the death message, use GetFullNetName to retrieve the NPC name to use in substitutions. This is intended for more advanced use cases, you should be modifying only DeathMessage for basic usages. Return false to skip the vanilla code for sending the message. This is useful if the death message is handled by this method or if the message should be skipped for any other reason, such as if there are multiple bosses. Returns true by default.
string ModifyTypeName(NPC npc, string typeName) static method same Allows you to modify the type name of this NPC dynamically.
bool CanGoToStatue(NPC npc, bool toKingStatue) static method same Whether this NPC can be teleported to a King or Queen statue. Returns false by default. Called in single player or on the server only.
void OnGoToStatue(NPC npc, bool toKingStatue) static method same Allows you to make things happen when this NPC teleports to a King or Queen statue. Called in single player or on the server only.
bool CanBeCaughtBy(NPC npc, Item item, Player player) static method same Allows you to determine whether the given item can catch this NPC. Return true or false to say this NPC can or cannot be caught, respectively, regardless of vanilla rules. Returns null by default, which allows vanilla's NPC catching rules to decide the target's fate. If this returns false, OnCatchNPC is never called. NOTE: this does not classify the given item as an NPC-catching tool, which is necessary for catching NPCs in the first place. To do that, you will need to use the "CatchingTool" set in ItemID.Sets. Called on the local client only.
void OnCaughtBy(NPC npc, Player player, Item item, bool failed) static method same Allows you to make things happen when the given item attempts to catch this NPC. Called on the local client only.
bool UsesPartyHat(NPC npc) static method same Allows you to determine whether this town NPC wears a party hat during a party. Returns true by default. Called on all clients.
void BuffTownNPC(ref float damageMult, ref int defense) static method differs Allows you to modify the stats of town NPCs. Useful for buffing town NPCs when certain bosses are defeated, etc. Called on the server and clients. tML: void BuffTownNPC(NPC npc, ref float damageMult, ref float attackSpeedMult, ref int defense, ref int maxLife)
void PartyHatPosition(NPC npc, ref Vector2 position, ref SpriteEffects spriteEffects) static method same Allows you to fully control the location of the party and sprite direction of the party while an NPC is wearing it. can be used instead of this hook for a constant Y offset. can be additionally be used for the Y offset for the Town NPC's animations. Called on all clients.
void ChatBubblePosition(NPC npc, ref Vector2 position, ref SpriteEffects spriteEffects) static method same Allows you to change the location and sprite direction of the chat bubble that shows up while hovering over a Town NPC. Called on all clients.
void ModifyHoverBoundingBox(NPC npc, ref Rectangle boundingBox) static method same Allows you to modify the bounding box for hovering over this NPC (affects things like whether or not its name is displayed). This hook won't be called if ShowNameOnHover is set to false. Called on the local client only.
bool PreHoverInteract(NPC npc, bool mouseIntersects) static method same Called when the NPC is selected via smart interact, or when the mouse is hovering over it. Right after ModifyHoverBoundingBox. Can be used to implement custom interact or hover behavior logic. By returning false, the vanilla code for town NPC chatting, drawing the chat bubble, and drawing the NPC name and life on the mouse is skipped. For example, the Old Shaking Chest NPC uses this to take a GoldenKey from the player and transform into Elder Slime. CanChat can be used to force smart interact to target this NPC despite as well, if desired. This hook won't be called if ShowNameOnHover is set to false. Called on the local client only.
bool NeedSaving(NPC npc) static method only here Makes this ModNPC save along the world even if it's not a townNPC. Defaults to false. NOTE: A town NPC will always be saved. NOTE: A NPC that needs saving will not despawn naturally.
ITownNPCProfile TownNPCProfile(NPC npc) static method only here Allows you to set the town NPC profile that this NPC uses. By default, returns null, meaning that the NPC doesn't use one.
bool DrawHealthBar(NPC npc, byte hbPosition, ref float scale, ref Vector2 position) static method differs Allows you to control how the health bar for this NPC is drawn. The hbPosition parameter is the same as Main.hbPosition; it determines whether the health bar gets drawn above or below the NPC by default. The scale parameter is the health bar's size. By default, it will be the normal 1f; most bosses set this to 1.5f. Return null to let the normal vanilla health-bar-drawing code to run. Return false to stop the health bar from being drawn. Return true to draw the health bar in the position specified by the position parameter (note that this is the world position, not screen position). Called on all clients. tML: bool DrawHealthBar(NPC npc, ref float scale)
bool CanBeHitByItem(NPC npc, Player player, Item item) static method same Allows you to determine whether this NPC can be hit by the given melee weapon when swung. Return true to allow hitting the NPC, return false to block hitting the NPC, and return null to use the vanilla code for whether the NPC can be hit. Returns null by default. Called on the local client only.
bool CanCollideWithPlayerMeleeAttack(NPC npc, Player player, Item item, Rectangle meleeAttackHitbox) static method same Allows you to determine whether an NPC can be collided with the player melee weapon when swung. Use CanBeHitByItem instead for Guide Voodoo Doll-type effects. Called on the local client only.
void ModifyIncomingHit(NPC npc, ref HitModifiers modifiers) static method same Allows you to use a custom damage formula for when this NPC takes damage from any source. For example, you can change the way defense works or use a different crit multiplier. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. Can be called on the local client or server, depending on who is dealing damage.
void ModifyHitByItem(NPC npc, Player player, Item item, ref HitModifiers modifiers) static method same Allows you to modify the damage, knockback, etc., that this NPC takes from a melee weapon. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. The final hit values such as the final damage can only be retrieved from the HitInfo in the OnHitByItem hook. Called on the local client only.
void OnHitByItem(NPC npc, Player player, Item item, in HitInfo hit, int damageDone) static method same Allows you to create special effects when this NPC is hit by a melee weapon. Changes to the hit such as the damage must be done by modifying the HitModifiers properties in the ModifyHitByItem hook. Called on the client doing the damage.
void NPCAI(NPC npc) static method same Runs the AI hooks and the game's AI.
bool PreAI(NPC npc) static method same Allows you to determine how this NPC behaves. Return false to stop the vanilla AI and the AI hook from being run. Returns true by default. Called on the server and clients.
void AI(NPC npc) static method same Allows you to determine how this NPC behaves. This will only be called if PreAI returns true. Called on the server and clients.
void PostAI(NPC npc) static method same Allows you to determine how any NPC behaves. This will be called regardless of what PreAI returns. Called on the server and remote clients.
void FindFrame(NPC npc, int frameHeight) static method same Allows you to modify the frame from this NPC's texture that is drawn, which is necessary in order to animate NPCs. Called on the server and clients.
void ResetEffects(NPC npc) static method same This is where you reset any fields you add to your subclass to their default states. This is necessary in order to reset your fields if they are conditionally set by a tick update but the condition is no longer satisfied. (Note: This hook is only really useful for GlobalNPC, but is included in ModNPC for completion.) Called on the server and clients.
bool CheckActive(NPC npc) static method same Whether or not to run the code for checking whether this NPC will remain active. Return false to stop this NPC from being despawned and to stop this NPC from counting towards the limit for how many NPCs can exist near a player. Returns true by default. See also DoesntDespawnToInactivityAndCountsNPCSlots for an option that still counts towards NPC spawn limits. Called on the server and clients.
bool CheckDead(NPC npc) static method same Whether or not this NPC should be killed when it reaches 0 health. You may program extra effects in this hook (for example, how Golem's head lifts up for the second phase of its fight). Return false to stop this NPC from being killed. Returns true by default. Called on the server and clients.
void HitEffect(NPC npc, in HitInfo hit) static method same Allows you to make things happen whenever this NPC is hit, such as creating dust or gores. Called on local, server, and remote clients. Usually when something happens when an NPC dies such as item spawning, you use NPCLoot, but you can use HitEffect paired with a check for if (NPC.life <= 0) to do client-side death effects, such as spawning dust, gore, or death sounds.
void UpdateLifeRegen(NPC npc, ref int damage) static method same Allows you to make the NPC either regenerate health or take damage over time by setting lifeRegen. This is useful for implementing damage over time debuffs such as Poisoned or OnFire. Regeneration or damage will occur at a rate of half of lifeRegen per second. Essentially, modders implementing damage over time debuffs should subtract from lifeRegen a number that is twice as large as the intended damage per second. See DamageOverTimeGlobalNPC.cs for an example of this. The damage parameter is the number that appears above the NPC's head if it takes damage over time. Multiple debuffs work together by following some conventions: lifeRegen should not be assigned a number, rather it should be subtracted from. damage should only be assigned if the intended popup text is larger then its current value. Called on the server and clients.
void ApplyDifficultyAndPlayerScaling(NPC npc, int numPlayers, float balance, float bossAdjustment) static method same Allows you to customize this NPC's stats when the difficulty is expert or higher. This runs after value, lifeMax, damage, knockBackResist have been adjusted for the current difficulty, (expert/master/FTW) It is common to multiply lifeMax by the balance factor, and sometimes adjust knockbackResist. Eg: lifeMax = (int)(lifeMax * balance * bossAdjustment)
void ModifyNPCLoot(NPC npc, NPCLoot npcLoot) static method same Allows you to add and modify NPC loot tables to drop on death and to appear in the Bestiary. The Basic NPC Drops and Loot 1.4 Guide explains how to use this hook to modify NPC loot. This hook only runs once during mod loading, any dynamic behavior must be contained in the rules themselves.
void ModifyGlobalLoot(GlobalLoot globalLoot) static method same Allows you to add and modify global loot rules that are conditional, i.e. vanilla's biome keys and souls. The Basic NPC Drops and Loot 1.4 Guide explains how to use this hook to modify npc loot.
bool PreKill(NPC npc) static method same Allows you to determine whether or not this NPC will do anything upon death (besides dying). This method can also be used to dynamically prevent specific item loot using blockLoot, but editing the drop rules themselves is usually the better approach. Returning false will skip dropping loot, the OnKill methods, and logic setting boss flags (DoDeathEvents). Returns true by default. Called in single player or on the server only.
void OnKill(NPC npc) static method same Allows you to make things happen when this NPC dies (for example, dropping items manually and setting ModSystem fields). Called in single player or on the server only. Most item drops should be done via drop rules registered in ModifyNPCLoot. Some dynamic NPC drops, such as additional hearts, are more suited for OnKill instead. MinionBossMinion.cs shows an example of an NPC that drops additional hearts. See lastInteraction and Player who killed NPC wiki section as well for determining which players attacked or killed this NPC. Bosses need to set flags when they are defeated, and some bosses run world generation code such as spawning new ore. MinionBossMinion.cs shows an example of these effects.
void BossLoot(NPC npc, ref int potionType, ref int potionStack, ref int heartStack) static method same Allows you to customize what happens when this boss dies, as well as letting you modify the type of potion it drops, the amount of potions, and the amount of hearts. Called in single player or on the server only.
void BossLoot(NPC npc, ref int potionType) static method differs Allows you to customize what happens when this boss dies, as well as letting you modify the type of potion it drops, the amount of potions, and the amount of hearts. Called in single player or on the server only. tML: void BossLoot(NPC npc, ref string name, ref int potionType)
void SendExtraAI(BinaryWriter writer, byte[] extraAI) static method same If you are storing AI information outside of the NPC.ai array, use this to send that AI information between clients and servers, which will be handled in ReceiveExtraAI. Called whenever SyncNPC is successfully sent, for example on NPC creation, on player join, or whenever NPC.netUpdate is set to true in the update loop for that tick. Only called on the server.
byte[] WriteExtraAI(NPC npc) static method same The bytes of SendExtraAI.
byte[] ReadExtraAI(BinaryReader reader) static method same The bytes for ReceiveExtraAI.
void ReceiveExtraAI(NPC npc, byte[] extraAI) static method same Use this to receive information that was sent in SendExtraAI. Called whenever SyncNPC is successfully received. Only called on the client.
bool CanBeHitByProjectile(NPC npc, Projectile projectile) static method same Allows you to determine whether this NPC can be hit by the given projectile. Return true to allow hitting the NPC, return false to block hitting the NPC, and return null to use the vanilla code for whether the NPC can be hit. Returns null by default. Can be called on the local client or server, depending on who owns the projectile.
void ModifyHitByProjectile(NPC npc, Projectile projectile, ref HitModifiers modifiers) static method same Allows you to modify the damage, knockback, etc., that this NPC takes from a projectile. This hook should be used ONLY to modify properties of the HitModifiers. Any extra side effects should occur in OnHit hooks instead. The final hit values such as the final damage can only be retrieved from the HitInfo in the OnHitByProjectile hook. Can be called on the local client or server, depending on who owns the projectile.
void OnHitByProjectile(NPC npc, Projectile projectile, in HitInfo hit, int damageDone) static method same Allows you to create special effects when this NPC is hit by a projectile. Changes to the hit such as the damage must be done by modifying the HitModifiers properties in the ModifyHitByProjectile hook. Can be called on the local client or server, depending on who owns the projectile.
void EditSpawnFlags(Spawner spawner) static method same Allows you to modify natural spawn flags for the given player before spawn rate, spawn range, and spawn tile are determined. Use this for player-level spawn context that should affect those later steps, such as biome, safe wall, or invasion flags. For example, a modded safe-zone effect could set spawner.noWorms = true before vanilla spawn logic uses that flag. Called in single player or on the server only.
void EditSpawnInfo(Spawner spawner) static method same Allows you to modify natural spawn information after the spawn tile has been chosen and before the spawn pool is evaluated. Use this for tile-level spawn context, such as water, granite, marble, spider cave, underground desert, spawn tile type, or spawn wall type. For example, a modded tile could set spawner.nearGranite = true so later SpawnChance and EditSpawnPool logic sees the chosen tile as granite-like. Called in single player or on the server only.
void EditSpawnRate(Player player, ref int spawnRate, ref int maxSpawns) static method same Allows you to modify the chance of NPCs spawning around the given player and the maximum number of NPCs that can spawn around the player. Lower spawnRates mean a higher chance for NPCs to spawn. Called in single player or on the server only.
void EditSpawnRange(Player player, ref int spawnRangeX, ref int spawnRangeY, ref int safeRangeX, ref int safeRangeY) static method same Allows you to modify the range at which NPCs can spawn around the given player. The spawnRanges determine that maximum distance NPCs can spawn from the player, and the safeRanges determine the minimum distance. Called in single player or on the server only.
int ChooseSpawn(Spawner spawner) static method same Picks the NPC to spawn from the pool.
int SpawnNPC(int type, int tileX, int tileY) static method same Allows you to customize how this NPC is created when it naturally spawns (for example, its position or ai array). Return the return value of NPC.NewNPC. By default this method spawns this NPC on top of the tile at the given coordinates. Called in single player or on the server only.
void CanTownNPCSpawn(int numTownNPCs) static method same Whether or not the conditions have been met for this town NPC to be able to move into town. For example, the Demolitionist requires that any player has an explosive. Town NPC spawn conditions typically check if specific bosses have been defeated (downedGolemBoss), the npc has been "saved" somewhere in the world, or any player has specific items in their inventory. To check for inventory items, iterate over ActivePlayers and check HasItem or CountItem, returning true if any player satisfies the requirement. To support allowing town NPC to respawn without needing to meet the original respawn requirements, a feature added in Terraria v1.4.4, store a bool in a ModSystem and check it. ExamplePerson.CanTownNPCSpawn and TownNPCRespawnSystem.cs show an example of this. Returns false by default, preventing the town NPC from spawning. Called in single player or on the server only.
bool CheckConditions(int type) static method same Allows you to define special conditions required for this town NPC's house. For example, Truffle requires the house to be in an aboveground mushroom biome. The left, right, top, and bottom parameters define the bounds of the room being checked. Methods like Housing_GetTestedRoomBounds and CountTileTypesInArea can facilitate implementing specific checks. Return false to prevent the npc from spawning due to failed condition checks. Called on the server and clients. The hint text explaining what a valid house is in the Housing button can be customized by adding the localization key Mods.YourModName.NPCs.YourNPCName.HousingText.HousingRequirements
List<string> ModifyNPCNameList(NPC npc, List<string> nameList) static method same Allows you to modify the list of names available to the given town NPC.
bool CanChat(NPC npc) static method same Allows you to determine whether this NPC can talk with the player. By default, returns if the NPC is a town NPC. This hook is not based on the type of the NPC, and is queried specifically on the ModNPC itself, regardless of if, for example, the type of the NPC instance is changed. Returning true in all circumstances will always make the NPC able to be chatted with no matter what else you do the NPC instance itself. Called on the local client only.
void GetChat(NPC npc, ref string chat) static method same Allows you to give this NPC a chat message when a player talks to it. By default returns something embarrassing. Called on the local client only.
void RegisterChatButtons(NPC npc, NPCInteractionList interactions) static method same Allows you to register chat buttons for this NPC. Use interactions to register new buttons. The "Close", "Happiness", and "Housing" buttons will automatically be registered before the buttons registered here. An NPC can only have 32 chat buttons shown at one time.
bool PreChatButtonClicked(NPCInteraction interaction) static method same Allows you to determine if something can happen whenever a button is clicked on this NPC's chat window. Return false to prevent the normal code for this button from running. Returns true by default. Called on the local client only.
void OnChatButtonClicked(NPCInteraction interaction) static method same Allows you to make something happen whenever a button is clicked on this NPC's chat window. Called on the local client only.
void AddShops(int type) static method same Allows you to add shops to this NPC, similar to adding recipes for items. Make a new NPCShop, and items to it, and call Register
void ModifyShop(NPCShop shop) static method same Allows you to modify existing shop. Be aware that this hook is called just one time during loading. The traveling merchant shop is passed here, but the per visit (info) entries cannot be modified here. Use SetupTravelShop instead.
void ModifyActiveShop(NPC npc, string shopName, Item[] items) static method same Allows you to modify the contents of a shop whenever player opens it. To create a shop, use AddShops Note that for special shops like travelling merchant, the shopName may not correspond to a NPCShop in the NPCShopDatabase Also note that unused slots in items are null while IsAir entries are entries that have a reserved slot (SlotReserved) but did not have their conditions met. These should not be overwritten. Called on the local client only.
void SetupTravelShop(int[] shop, ref int nextSlot) static method same Allows you to add items to the traveling merchant's shop. Add an item by setting shop[nextSlot] to the ID of the item you are adding then incrementing nextSlot. In the end, nextSlot must have a value of 1 greater than the highest index in shop that represents an item ID. If you want to remove an item, you will have to be familiar with programming. Called in single player or on the server only.
void TownNPCAttackStrength(NPC npc, ref int damage, ref float knockback) static method same Allows you to determine the damage and knockback of this town NPC's attack before the damage is scaled. (More information on scaling in GlobalNPC.BuffTownNPCs.) Called on the server and clients.
void TownNPCAttackCooldown(NPC npc, ref int cooldown, ref int randExtraCooldown) static method same Allows you to determine the cooldown between each of this town NPC's attack. The cooldown will be a number greater than or equal to the first parameter, and less then the sum of the two parameters. Called on the server and clients.
void TownNPCAttackProj(NPC npc, ref int projType, ref int attackDelay) static method same Allows you to determine the projectile type of this town NPC's attack, and how long it takes for the projectile to actually appear. This hook is only used when the town NPC has an attack type (AttackType) of 0 (throwing), 1 (shooting), or 2 (magic). Called on the server and clients.
void TownNPCAttackProjSpeed(NPC npc, ref float multiplier, ref float gravityCorrection, ref float randomOffset) static method same Allows you to determine the speed at which this town NPC throws a projectile when it attacks. Multiplier is the speed of the projectile, gravityCorrection is how much extra the projectile gets thrown upwards, and randomOffset allows you to randomize the projectile's velocity in a square centered around the original velocity. This hook is only used when the town NPC has an attack type (AttackType) of 0 (throwing), 1 (shooting), or 2 (magic). Called on the server and clients.
void TownNPCAttackShoot(NPC npc, ref bool inBetweenShots) static method same Allows you to tell the game that this town NPC has already created a projectile and will still create more projectiles as part of a single attack so that the game can animate the NPC's attack properly. Only used when the town NPC has an attack type (AttackType) of 1 (shooting). Called on the server and clients.
void TownNPCAttackMagic(NPC npc, ref float auraLightMultiplier) static method same Allows you to control the brightness of the light emitted by this town NPC's aura when it performs a magic attack. Only used when the town NPC has an attack type (AttackType) of 2 (magic) Called on the server and clients.
void TownNPCAttackSwing(NPC npc, ref int itemWidth, ref int itemHeight) static method same Allows you to determine the width and height of the item this town NPC swings when it attacks, which controls the range of this NPC's swung weapon. Only used when the town NPC has an attack type (AttackType) of 3 (swinging). Called on the server and clients.
void DrawTownAttackGun(NPC npc, ref Texture2D item, ref Rectangle itemFrame, ref float scale, ref int horizontalHoldoutOffset) static method same Allows you to customize how this town NPC's weapon is drawn when this NPC is shooting (this NPC must have an attack type (AttackType) of 1). scale is a multiplier for the item's drawing size, item is the Texture2D instance of the item to be drawn, itemFrame is the section of the texture to draw, and horizontalHoldoutOffset is how far away the item should be drawn from the NPC. To use an actual item sprite, use Main.GetItemDrawFrame(itemTypeHere, out item, out itemFrame); horizontalHoldoutOffset = (int)Main.DrawPlayerItemPos(1f, itemType).X - someOffsetHere Called on all clients.
void DrawTownAttackSwing(NPC npc, ref Texture2D item, ref Rectangle itemFrame, ref int itemSize, ref float scale, ref Vector2 offset) static method same Allows you to customize how this town NPC's weapon is drawn when this NPC is swinging it (this NPC must have an attack type (AttackType) of 3). item is the Texture2D instance of the item to be drawn, itemFrame is the section of the texture to draw, itemSize is the width and height of the item's hitbox (the same values for TownNPCAttackSwing), scale is the multiplier for the item's drawing size, and offset is the offset from which to draw the item from its normal position. The item texture can be any texture, but if it is an item texture you can use GetItemDrawFrame to set item and itemFrame easily. Called on all clients.
int BannerItemToNPC(int itemType) static method not here Returns the type of a ModNPC corresponding to the provided banner item type. Note that this is equivalent to the banner type as well, since ModNPC type and banner type are the same. Returns -1 if not found.
bool SavesAndLoads(NPC npc) static method not here Internal here.

tModLoader's NPCLoader also has 1 public methods that only run the hooks of the same name. Here those runners are internal. Override the hook in your class instead.

NPCLoot

struct Terraria.ModLoader.NPCLoot : ILoot

Provides access to ItemDropDatabase's methods specific to this NPC type.

Member Kind tModLoader What it does
new NPCLoot(int npcNetId, ItemDropDatabase database) constructor same Creates an instance.
List<IItemDropRule> Get(bool includeGlobalDrops) method same The rules of this NPC.
IItemDropRule Add(IItemDropRule entry) method same Adds a rule.
IItemDropRule Remove(IItemDropRule entry) method same Removes a specific IItemDropRule from this NPC type. Note that entry must be an existing IItemDropRule instance retrieved from Get, not a newly created instance.
void RemoveWhere(Predicate<IItemDropRule> predicate, bool includeGlobalDrops) method same Removes the rules that match.

NPCShop

class Terraria.ModLoader.NPCShop : AbstractNPCShop

A town NPC's shop: new NPCShop(Type).Add<MyItem>().Register().

Member Kind tModLoader What it does
IReadOnlyList<Entry> Entries property same Every line.
IEnumerable<Entry> AllEntries override same Every line.
bool FillLastSlot property same Whether the last slot is used.
new NPCShop(int npcType, string name) constructor same Creates an instance.
Entry GetEntry(int item) method same The line of an item.
bool TryGetEntry(int item, out Entry entry) method same Finds the line of an item.
NPCShop AllowFillingLastSlot() method same Lets the shop use its last slot.
NPCShop Add(params Entry[] added) method same Adds a line.
NPCShop Add(Item item, params Condition[] conditions) method same Adds a line.
NPCShop Add(int item, params Condition[] conditions) method same Adds a line.
NPCShop Add<T>(params Condition[] conditions) method same Adds a line.
NPCShop InsertBefore(int target, int item, params Condition[] conditions) method same Adds a line before another one.
NPCShop InsertAfter(int target, int item, params Condition[] conditions) method same Adds a line after another one.
NPCShop InsertBefore(int target, Item item, params Condition[] conditions) method same Adds a line before another one.
NPCShop InsertAfter(int target, Item item, params Condition[] conditions) method same Adds a line after another one.
NPCShop InsertBefore(Entry target, Item item, params Condition[] conditions) method same Adds a line before another one.
NPCShop InsertAfter(Entry target, Item item, params Condition[] conditions) method same Adds a line after another one.
void FinishSetup() override same Sorts the lines after all mods have added theirs.
void FillShop(ICollection<Item> items, NPC npc) override same Fills the shop's slots with what is active.
void FillShop(Item[] items, NPC npc, out bool overflow) override same Fills the shop's slots with what is active.
void Open() method only here Opens the shop for the local player.

NPCShop.Entry

class Terraria.ModLoader.NPCShop.Entry : Entry

One line of an NPCShop.

Member Kind tModLoader What it does
bool OrdersLast property same Whether it goes after the rest.
bool SlotReserved property same Whether its slot stays even when its conditions fail.
new Entry(int item, params Condition[] conditions) constructor same Creates an instance.
new Entry(Item item, params Condition[] conditions) constructor same Creates an instance.
Entry SortBefore(Entry target) method same Puts it before another line.
Entry SortAfter(Entry target) method same Puts it after another line.
Entry AddCondition(Condition condition) method same Adds a condition.
Entry OrderLast() method same Puts it after the rest.
Entry ReserveSlot() method same Reserves a slot for this entry even if its conditions are not met (ConditionsMet). This can be used to create a defined shop layout similar to the Tavernkeep shop.
Entry AddShopOpenedCallback(Action<Item, NPC> callback) method same Runs a method when the shop opens, to change the item.
void OnShopOpen(Item item, NPC npc) method same Runs those methods.

NPCShopDatabase

static class Terraria.ModLoader.NPCShopDatabase

Every shop by name. GetShopName builds the name.

Member Kind tModLoader What it does
IEnumerable<AbstractNPCShop> AllShops static property same Every shop.
ISet<string> NoPylons static field same The shops that do not sell pylons.
string GetShopName(int npcType, string shopName) static method same Gets a shop name (identifier) in the format matching FullName Can be used with TryGetNPCShop and ModifyActiveShop
AbstractNPCShop GetShop(string fullName) static method only here A shop by name.
bool TryGetNPCShop(string fullName, out NPCShop shop) static method differs Finds a shop by name. tML: bool TryGetNPCShop(string fullName, out AbstractNPCShop shop)
void AddShop(AbstractNPCShop shop) static method only here Adds a shop.
void OpenShop(string fullName) static method only here Opens a shop by name.
string GetShopNameFromVanillaIndex(int index) static method not here Internal here.
void Initialize() static method not here Internal here.
IEnumerable<Entry> GetPylonEntries() static method not here Internal here.

NPCSpawnInfo

struct Terraria.ModLoader.NPCSpawnInfo · only in Bunny Loader

Where and how an NPC would spawn, passed to SpawnChance.

Member Kind tModLoader What it does
Spawner Spawner field only here The game's spawn state behind this.
int SpawnTileX field only here Tile column of the spawn.
int SpawnTileY field only here Tile row of the spawn.
int SpawnTileType field only here The tile under the spawn.
int GroundTileY field only here The row of the ground.
int SpawnWallType field only here The wall at the spawn.
Player Player field only here The player the spawn is for.
int PlayerFloorX field only here The player's tile column.
int PlayerFloorY field only here The tile row under the player.
bool Sky field only here In space.
bool Lihzahrd field only here In the Lihzahrd temple.
bool PlayerSafe field only here The player is behind a safe wall.
bool Invasion field only here An invasion is near the player.
bool Water field only here In water.
bool Granite field only here In a granite cave.
bool Marble field only here In a marble cave.
bool SpiderCave field only here In a spider cave.
bool PlayerInTown field only here The player is in a town.
bool DesertCave field only here In the underground desert.
bool SafeRangeX field only here Inside the safe range around spawn.

Profiles

class Terraria.GameContent.Profiles

Ready-made ITownNPCProfile classes.

Member Kind tModLoader What it does

Profiles.DefaultNPCProfile

class Terraria.GameContent.Profiles.DefaultNPCProfile : ITownNPCProfile

Class that is some-what identical to that allows for modded texture usage. Also allows for any potential children classes to mess with the fields.

Member Kind tModLoader What it does
new DefaultNPCProfile(string texture, int headIndex, string partyTexture) constructor same Creates an instance.
int RollVariation() method same Always 0.
string GetNameForVariant(NPC npc) method same Null, so the name is random.
Asset<Texture2D> GetTextureNPCShouldUse(NPC npc) method same Its texture, with the party version when there is one.
int GetHeadTextureIndex(NPC npc) method same Its head slot.
int currentHeadSlot field not here Internal to the class.
Asset<Texture2D> defaultTexture field not here Internal to the class.
Asset<Texture2D> partyTexture field not here Internal to the class.

Profiles.StackedNPCProfile

class Terraria.GameContent.Profiles.StackedNPCProfile : ITownNPCProfile

A profile that picks from others, usually normal and shimmered.

Member Kind tModLoader What it does
new StackedNPCProfile(params ITownNPCProfile[] profilesInOrderOfVariants) constructor same Creates an instance.
int RollVariation() method same Picks a variant from the stacked profiles.
string GetNameForVariant(NPC npc) method same The name of the profile in use.
Asset<Texture2D> GetTextureNPCShouldUse(NPC npc) method same The texture of the profile in use.
int GetHeadTextureIndex(NPC npc) method same The head of the profile in use.

SpawnCondition

class Terraria.ModLoader.Utilities.SpawnCondition

This serves as a central class to help modders spawn their NPCs. It's basically the vanilla spawn code if-else chains condensed into objects. See ExampleMod for usages.

Members: Chance, Active, NebulaTower, VortexTower, StardustTower, SolarTower, Sky, Invasion, GoblinArmy, FrostLegion, Pirates, MartianMadness, Bartender, SpiderCave, DesertCave, HardmodeJungleWater, HardmodeCrimsonWater, Ocean, OceanAngler, OceanMonster, BeachAngler, JungleWater, CavePiranha, CaveJellyfish, WaterCritter, CorruptWaterCritter, OverworldWaterCritter, OverworldWaterSurfaceCritter, OverworldUnderwaterCritter, DefaultWaterCritter, BoundCaveNPC, TownCritter, TownWaterCritter, TownOverworldWaterCritter, TownOverworldWaterSurfaceCritter, TownOverworldUnderwaterCritter, TownDefaultWaterCritter, TownSnowCritter, TownJungleCritter, TownGeneralCritter, Dungeon, DungeonGuardian, DungeonNormal, Meteor, OldOnesArmy, FrostMoon, PumpkinMoon, SolarEclipse, HardmodeMushroomWater, OverworldMushroom, UndergroundMushroom, CorruptWorm, UndergroundMimic, OverworldMimic, Wraith, HoppinJack, DoctorBones, LacBeetle, WormCritter, MouseCritter, SnailCritter, FrogCritter, HardmodeJungle, JungleTemple, UndergroundJungle, SurfaceJungle, SandstormEvent, Mummy, DarkMummy, LightMummy, OverworldHallow, EnchantedSword, Crimson, Corruption, Overworld, IceGolem, RainbowSlime, AngryNimbus, MartianProbe, OverworldDay, OverworldDaySnowCritter, OverworldDayGrassCritter, OverworldDaySandCritter, OverworldMorningBirdCritter, OverworldDayBirdCritter, KingSlime, OverworldDayDesert, GoblinScout, OverworldDayRain, OverworldDaySlime, OverworldNight, OverworldFirefly, OverworldNightMonster, Underground, Underworld, Cavern


← Items  ·  Projectiles →

Clone this wiki locally