tModLoader v2024.10
A mod to make and play Terraria mods
NPC Class Reference

Inherits Entity, and IEntityWithGlobals< GlobalNPC >.

Classes

struct  HitInfo
 Represents a finalized damage calculation for damage about to be applied to an NPC. This is the result of the all modifications done previously in a HitModifiers. More...
 
struct  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. More...
 

Public Member Functions

void AddBuff (int type, int time, bool quiet=false)
 Gives this NPC the provided buff. This accounts for if the NPC is immune to the buff.
If the NPC already has the buff, the re-apply logic will happen. Vanilla buff types are found in BuffID and modded buffs are typically retrieved using ModContent.BuffType<T>.
The quiet parameter will determine if the network sync message should happen. This should always stay false. More...
 
void AI ()
 
void AI_000_TransformBoundNPC (int playerID, int npcType)
 
void AI_001_SetRainbowSlimeColor ()
 
NPC AI_113_WindyBalloon_GetSlaveNPC ()
 
bool AI_120_HallowBoss_IsGenuinelyEnraged ()
 
bool AI_120_HallowBoss_IsInPhase2 ()
 
void AI_122_PirateGhost ()
 
bool AI_AttemptToFindTeleportSpot (ref Vector2 chosenTile, int targetTileX, int targetTileY, int rangeFromTargetTile=20, int telefragPreventionDistanceInTiles=5, int solidTileCheckFluff=1, bool solidTileCheckCentered=false, bool teleportInAir=false)
 
bool AnyInteractions ()
 Returns true if any player has damaged this NPC. Individual player participation can be determined by checking playerInteraction directly. Use GetWereThereAnyInteractions if realLife might be in use. More...
 
void ApplyInteraction (int player)
 
void AttemptToConvertNPCToEvil (bool crimson)
 
int BannerID ()
 
void BecomeImmuneTo (int buffType)
 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 BuffID.Sets.GrantImmunityWith). This method can be followed by ClearImmuneToBuffs(out bool) if the NPC should clear any buff it currently has that it is now immune to. More...
 
void BigMimicSpawnSmoke ()
 
void BloodNautilus_GetMouthPositionAndRotation (out Vector2 mouthPosition, out Vector2 mouthDirection)
 
bool Boss_CanShootExtraAt (int playerIndex, int rotationIndexToAttack, int rotationSize, float attackScanDistance, bool alwaysSkipMainTarget=true)
 
HitInfo CalculateHitInfo (int damage, int hitDirection, bool crit=false, float knockBack=0f, DamageClass damageType=null, bool damageVariation=false, float luck=0)
 Runs NPCLoader.ModifyIncomingHit hooks and and does the full damage calculations.
The result HitInfo.Damage will contain the health the NPC will lose when applied.
More...
 
bool CanApplyHunterPotionEffects ()
 
bool CanBeChasedBy (object attacker=null, bool ignoreDontTakeDamage=false)
 Returns true if this NPC should be considered an enemy to attack. Used by various player, projectile, mount, and town npc logic. For example homing projectiles like Chlorophyte bullet won't target friendly NPC, critters, or NPC that are currently flagged as invulnerable. Note that the attacker parameter is unused. The logic checks that the NPC meets all of the following criteria: Entity.active, chaseable, lifeMax > 5 (to ignore critters), dontTakeDamage (unless ignoreDontTakeDamage ) is true), not friendly, and not immortal. More...
 
bool CanReflectProjectile (Projectile proj)
 
void CheckActive ()
 
void checkDead ()
 
void CheckDrowning ()
 
void ClearImmuneToBuffs (out bool anyBuffsCleared)
 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(int).

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. More...
 
object Clone ()
 
void CloneDefaults (int Type)
 
void CopyInteractions (NPC npc)
 
void DelBuff (int buffIndex)
 Removes the buff at the provided index and shuffles the remaining buff indexes down to fill the gap. The buff types and times will then be synced to clients. This method should only be called on the server or in single player. More...
 
void DiscourageDespawn (int despawnTime)
 
bool DoesntDespawnToInactivity ()
 
bool DoesntDespawnToInactivityAndCountsNPCSlots ()
 
void DropItemInstanced (Vector2 Position, Vector2 HitboxSize, int itemType, int itemStack=1, bool interactionRequired=true)
 
void DropTombstoneTownNPC (NetworkText deathText)
 
void EncourageDespawn (int despawnTime)
 
bool ExcludedFromDeathTally ()
 
void FaceTarget ()
 
int FindBuffIndex (int type)
 
int FindClosestPlayer ()
 
int FindClosestPlayer (out float distanceToPlayer)
 
void FindFrame ()
 
Color GetAlpha (Color newColor)
 
int GetAttackDamage_ForProjectiles (float normalDamage, float expertDamage)
 
int GetAttackDamage_ForProjectiles_MultiLerp (float normalDamage, float expertDamage, float masterDamage)
 
int GetAttackDamage_LerpBetweenFinalValues (float normalDamage, float expertDamage)
 
float GetAttackDamage_LerpBetweenFinalValuesFloat (float normalDamage, float expertDamage)
 
int GetAttackDamage_ScaledByStrength (float normalDamage)
 
string GetBestiaryCreditId ()
 
Color GetBestiaryEntryColor ()
 
float GetBossHeadRotation ()
 
SpriteEffects GetBossHeadSpriteEffects ()
 
int GetBossHeadTextureIndex ()
 
string GetChat ()
 
Color GetColor (Color newColor)
 
NetworkText GetFullNetName ()
 
NetworkText GetGivenNetName ()
 
NetworkText GetGivenOrTypeNetName ()
 
GetGlobalNPC< T > ()
 Gets the instance of the specified GlobalNPC type. This will throw exceptions on failure. More...
 
GetGlobalNPC< T > (T baseInstance)
 Gets the local instance of the type of the specified GlobalNPC instance. This will throw exceptions on failure. More...
 
void GetImmuneTime (int fromWho, int time)
 
HitModifiers GetIncomingStrikeModifiers (DamageClass damageType, int hitDirection, bool ignoreArmorDebuffs=false)
 Initializes a HitModifiers calculation with the properties of this NPC, including calling NPCLoader.ModifyIncomingHit More...
 
float GetLifePercent ()
 
void GetLifeStats (out int statLife, out int statLifeMax)
 
Color GetMagicAuraColor ()
 
NPCSpawnParams GetMatchingSpawnParams ()
 
Vector2 GetMechQueenCenter ()
 
float GetMyBalance ()
 
string getNewNPCName ()
 
Color GetNPCColorTintedByBuffs (Color npcColor)
 
PartyHatColor GetPartyHatColor ()
 
int GetPartyHatGore ()
 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. More...
 
Rectangle getRect ()
 
Color GetShimmerColor (Color newColor)
 
int GetShootingFrame (float circleY)
 
IEntitySource GetSource_Buff (int buffIndex)
 
bool GetSpecialEventTextIfNotEmpty (string specialTextKey, object substitutes, ref string specialEventText)
 
Tuple< Vector2, float > GetSwingStats (int swingMax, int swingCurrent, int aimDir, int itemWidth, int itemHeight)
 
NPCAimedTarget GetTargetData (bool ignorePlayerTankPets=true)
 
void GetTileCollisionParameters (out Vector2 cPosition, out int cWidth, out int cHeight)
 
NetworkText GetTypeNetName ()
 
bool GetWereThereAnyInteractions ()
 Returns true if any player has damaged this NPC. Individual player participation can be determined by checking playerInteraction directly. More...
 
bool HasBuff (int type)
 Returns whether or not this NPC currently has a (de)buff of the provided type.
 
bool HasBuff< T > ()
 
bool HasLuckTextForWizard (out string specialEventText)
 
bool HasSpecialEventText (string specialTextCategoryKey, out string specialEventText)
 
void HealEffect (int healAmount, bool broadcast=true)
 Spawns a CombatText indicating the NPC healed healAmount life and syncs it if broadcast is true. Note that this doesn't actually heal the NPC, it only spawns the floating text. To heal an NPC, NPC.life must be increased without exceeding NPC.lifeMax, HealEffect(int, bool) should be called, and NPC.netUpdate should be set to true. Since the server has ownership over NPC, this should only be called on the server in multiplayer situations.
 
void HitEffect (HitInfo hit)
 
void HitEffect (int hitDirection=0, double dmg=10.0, bool? instantKill=null)
 
bool HittableForOnHitRewards ()
 
void IdleSounds ()
 
bool IsDamageDodgeable ()
 
bool IsNPCValidForBestiaryKillCredit ()
 
void moneyPing (Vector2 pos)
 
bool NPCCanStickToWalls ()
 
void NPCLoot ()
 
void PlayerInteraction (int player)
 
void PopAllAttachedProjectilesAndTakeDamageForThem ()
 
void ReflectProjectile (Projectile proj)
 
void ReflectProjectiles (Rectangle myRect)
 
void RequestBuffRemoval (int buffTypeToRemove)
 Removes the buff type and shuffles the remaining buff indexes down to fill the gap. Note that only buffs contained in BuffID.Sets.CanBeRemovedByNetMessage can be removed with this method. The intention is that those specific buffs are "owned" by the player who inflicts them, so they can be freely removed by multiplayer clients.

In all other cases code running on the server or in single player is in charge of the NPC debuffs and NPC.DelBuff should be used directly. More...
 
bool RerollVariation ()
 
void ScaleStats (int? activePlayersCount, GameModeData gameModeData, float? strengthOverride)
 
void ScaleStats_UseStrengthMultiplier (float strength)
 
void SetDefaults (int Type, NPCSpawnParams spawnparams=default(NPCSpawnParams))
 
void SetDefaults_ForNetId (int Type, float scaleOverride)
 
void SetDefaults_ForNetId (int Type, NPCSpawnParams spawnparams, float scaleOverride)
 
void SetDefaultsKeepPlayerInteraction (int Type)
 
void SetFrameSize ()
 
void SetNetShimmerEffect ()
 
bool ShouldBestiaryGirlBeLycantrope ()
 
bool ShouldFaceTarget (ref NPCUtils.TargetSearchResults searchResults, NPCUtils.TargetType? overrideTargetType=null)
 
void SimpleFlyMovement (Vector2 desiredVelocity, float moveSpeed)
 
int SimpleStrikeNPC (int damage, int hitDirection, bool crit=false, float knockBack=0f, DamageClass damageType=null, bool damageVariation=false, float luck=0, bool noPlayerInteraction=false)
 Calls CalculateHitInfo, StrikeNPC(HitInfo, bool, bool) and then NetMessage.SendStrikeNPC (in multiplayer)
More...
 
void SitDown (Point anchorTilePosition, out int direction, out Vector2 bottom)
 Helper method for getting the parameters for seating a town NPC. Assumes the tile at anchorTilePosition is a valid tile for sitting
 
void SpawnWithHigherTime (int timeMult)
 
void StrikeInstantKill ()
 Helper method for calling StrikeNPC(HitInfo, bool, bool) with a HitInfo.InstantKill strike.
Use to butcher your own NPCs.
Not recommended for use on multiplayer clients because the net packet will trigger PlayerInteraction on the server.
 
int StrikeNPC (HitInfo hit, bool fromNet=false, bool noPlayerInteraction=false)
 Directly deals damage to the NPC, spawns combat text, plays hit sound, deals knockback based on the provided HitInfo
Calls HitEffect(HitInfo) and associated hooks after dealing damage.
Calls checkDead
Does not automatically send packets. Use NetMessage.SendStrikeNPC to synchronize hits. More...
 
void TargetClosest (bool faceTarget=true)
 Targets the closest alive Player and optionally faces towards that Player. This will set target to the targeted player, as well as Entity.direction if faceTarget is true. Make sure to check HasValidTarget before accessing target. More...
 
void TargetClosest_WOF (bool faceTarget=true)
 
void TargetClosestUpgraded (bool faceTarget=true, Vector2? checkPosition=null)
 
void Teleport (Vector2 newPos, int Style=0, int extraInfo=0)
 
override string ToString ()
 
void Transform (int newType)
 
void TransformVisuals (int oldType, int newType)
 
bool TryGetGlobalNPC< T > (out T result)
 Gets the instance of the specified GlobalNPC type. More...
 
bool TryGetGlobalNPC< T > (T baseInstance, out T result)
 Safely attempts to get the local instance of the type of the specified GlobalNPC instance. More...
 
void TryPortalJumping ()
 
void TweakSwingStats (int swingMax, int swingCurrent, int aimDir, ref Rectangle itemRectangle)
 
void UpdateAltTexture ()
 
void UpdateHomeTileState (bool homeless, int x, int y)
 
void UpdateNPC (int i)
 
void UpdateNPC_BuffSetFlags (bool lowerBuffTime=true)
 
bool UsesPartyHat ()
 
void VanillaAI ()
 
void VanillaFindFrame (int num, bool isLikeATownNPC, int type)
 
- Public Member Functions inherited from Entity
float AngleFrom (Vector2 Source)
 
float AngleTo (Vector2 Destination)
 
Vector2 DirectionFrom (Vector2 Source)
 
Vector2 DirectionTo (Vector2 Destination)
 
float Distance (Vector2 Other)
 
float DistanceSQ (Vector2 Other)
 
IEntitySource GetSource_CatchEntity (Entity caughtEntity, string? context=null)
 
IEntitySource GetSource_Death (string? context=null)
 
IEntitySource GetSource_DropAsItem (string? context=null)
 
IEntitySource GetSource_FromAI (string? context=null)
 
IEntitySource GetSource_FromThis (string? context=null)
 
IEntitySource GetSource_GiftOrReward (string? context=null)
 
IEntitySource GetSource_Loot (string? context=null)
 
IEntitySource GetSource_Misc (string context)
 
IEntitySource GetSource_OnHit (Entity victim, string? context=null)
 
IEntitySource GetSource_OnHurt (Entity? attacker, string? context=null)
 
IEntitySource GetSource_ReleaseEntity (string? context=null)
 
IEntitySource GetSource_TileInteraction (int tileCoordsX, int tileCoordsY, string? context=null)
 
bool WithinRange (Vector2 Target, float MaxRange)
 

Static Public Member Functions

static Color AI_121_QueenSlime_GetDustColor ()
 
static bool AnyDanger (bool quickBossNPCCheck=false, bool ignorePillarsAndMoonlordCountdown=false)
 
static bool AnyHelpfulFairies ()
 
static bool AnyNPCs (int Type)
 Returns true if there are any active NPC in the world of the given NPC type (NPC.type). More...
 
static bool AnyoneNearCultists ()
 
static bool BigMimicSummonCheck (int x, int y, Player user)
 
static Color buffColor (Color newColor, float R, float G, float B, float A)
 
static bool BusyWithAnyInvasionOfSorts ()
 
static bool CanReleaseNPCs (int who)
 
static bool CheckCatchNPC (NPC npc, Rectangle catchToolRectangle, Item item, Player player, bool lavaProofTool=false)
 Runs most code related to the process of checking whether or not an NPC can be caught.
After that, CombinedHooks.OnCatchNPC is run, followed by the code responsible for catching the NPC if applicable.
You will need to call this manually if you want to make an NPC-catching tool which acts differently from vanilla's, such as one that uses a projectile instead of an item.
As a note, if calling this manually, you will need to check npc.active && npc.catchItem > 0 yourself. More...
 
static void ClearFoundActiveNPCs ()
 
static void ClearFoundNPCTypesForBestiary ()
 
static int CountNPCS (int Type)
 Returns the number of active NPC in the world of the given NPC type (NPC.type). More...
 
static bool DespawnEncouragement_AIStyle2_FloatingEye_IsDiscouraged (int npcID, Vector2 npcPosition, int target=255)
 
static bool DespawnEncouragement_AIStyle3_Fighters_CanBeBusyWithAction (int npcID)
 
static bool DespawnEncouragement_AIStyle3_Fighters_NotDiscouraged (int npcID, Vector2 position, NPC npcInstance)
 
static void FairyEffects (Vector2 Position, int type)
 
static bool FindCattailTop (int landX, int landY, out int cattailX, out int cattailY)
 
static int FindFirstNPC (int Type)
 Returns the index within Main.npc of the the first active NPC in the world of the given NPC type (NPC.type). More...
 
static bool FindTreeBranch (int landX, int landY, out int treeBranchX, out int treeBranchY)
 
static int GetActivePlayerCount ()
 
static int GetAvailableAmountOfNPCsToSpawnUpToSlot (int amountWeWant, int highestNPCSlotIndexWeWillPick=100)
 
static float GetBalance ()
 
static IEntitySource GetBossSpawnSource (int targetPlayerIndex)
 
static int GetBrainOfCthuluCreepersCount ()
 
static int GetDestroyerSegmentsCount ()
 
static int GetEaterOfWorldsSegmentsCount ()
 
static int GetEaterOfWorldsSegmentsCountByGamemode (int gamemode)
 
static string GetFirstNPCNameOrNull (int npcType)
 Returns the GivenOrTypeName of the first active NPC of the given type in the world. If not found, null is returned. More...
 
static string GetFullnameByID (int npcID)
 Returns the FullName of the first active NPC of the given type in the world. If not found, the type name is returned instead. More...
 
static void GetMeleeCollisionData (Rectangle victimHitbox, int enemyIndex, ref int specialHitSetter, ref float damageMultiplier, ref Rectangle npcRect)
 
static int GetNPCInvasionGroup (int npcID)
 Gets the InvasionID associated with the given NPC type (NPC.type). More...
 
static bool GetNPCLocation (int i, bool seekHead, bool averageDirection, out int index, out Vector2 pos)
 
static void GetStatScalingFactors (int numPlayers, out float balance, out float boost)
 
static void HaveDryadDoStardewAnimation ()
 
static void HealEffect (Rectangle r, int healAmount, bool broadcast=true)
 

This particular overload allows customizing the spawn location of the text.
 
static int[,,,] InitializeMoonLordAttacks ()
 
static int[,] InitializeMoonLordAttacks2 ()
 
static bool IsADeerclopsNearScreen ()
 
static bool IsDeerclopsHostile ()
 
static bool IsValidSpawningGroundTile (int x, int y)
 
static void LadyBugKilled (Vector2 Position, bool GoldLadyBug=false)
 
static bool MechSpawn (float x, float y, int type)
 Use to check if a mechanism is allowed to spawn an NPC of the provided type at the provided world coordinates. Checks nearby area to see if the Spawn Limitshave been reached.
 
static bool NearSpikeBall (int x, int y)
 
static int NewNPC (IEntitySource source, int X, int Y, int Type, int Start=0, float ai0=0f, float ai1=0f, float ai2=0f, float ai3=0f, int Target=255)
 Spawns an NPC into the game world with the given type.
This method should not be called on multiplayer clients.
The X and Y parameters dictate the centered spawn position.
>ai0, ai1, ai2, ai3 will initialize the NPC.ai[] array with the supplied values. This can be used to pass in information to the NPC. The NPC AI code will have to be written to utilize those values.
More...
 
static NPC NewNPCDirect (IEntitySource source, int x, int y, int type, int start=0, float ai0=0f, float ai1=0f, float ai2=0f, float ai3=0f, int target=255)
 

This particular overload returns the actual NPC instance rather than the index of the spawned NPC within the Main.npc array.
A short-hand for More...
 
static NPC NewNPCDirect (IEntitySource source, Vector2 position, int type, int start=0, float ai0=0f, float ai1=0f, float ai2=0f, float ai3=0f, int target=255)
 

This particular overload returns the actual NPC instance rather than the index of the spawned NPC within the Main.npc array. It also uses a Vector2 for the spawn position instead of X and Y.
A short-hand for More...
 
static void OnGameEventClearedForTheFirstTime (int gameEventId)
 
static int ReleaseNPC (int x, int y, int Type, int Style, int who)
 
static bool RerollVariationForNPCType (int npcType)
 
static void ResetBadgerHatTime ()
 
static void ResetKillCount ()
 
static void ResetNetOffsets ()
 
static void ResetRemixHax ()
 
static void SetEventFlagCleared (ref bool eventFlag, int gameEventId)
 
static void setFireFlyChance ()
 
static void setNPCName (string newName, int npcType, bool resetExtras=false)
 
static void SetRemixHax ()
 
static void SetWorldSpecificMonstersByWorldID ()
 
static bool ShouldEmpressBeEnraged ()
 
static void SlimeRainSpawns (int plr)
 
static bool SpawnAllowed_ArmsDealer ()
 
static bool SpawnAllowed_Demolitionist ()
 
static bool SpawnAllowed_DyeTrader ()
 
static bool SpawnAllowed_Merchant ()
 
static bool SpawnAllowed_Nurse ()
 
static void SpawnBoss (int spawnPositionX, int spawnPositionY, int Type, int targetPlayerIndex)
 
static void SpawnFaelings (int plr)
 
static bool Spawning_FlyingAntlionCheck (int x, int y)
 
static bool Spawning_SandstoneCheck (int x, int y)
 
static bool SpawnMechQueen (int onWhichPlayer)
 
static void SpawnNPC ()
 
static int SpawnNPC_GetGemBunnyToSpawn ()
 
static int SpawnNPC_GetGemSquirrelToSpawn ()
 
static void SpawnNPC_SpawnFrog (int spawnTileX, int spawnTileY, int plr)
 
static void SpawnOnPlayer (int plr, int Type)
 
static void SpawnSkeletron (int onWho)
 
static bool SpawnTileOrAboveHasAnyWallInSet (int x, int y, bool[] wallTypes)
 
static void SpawnWOF (Vector2 pos)
 
static void TransformCopperSlime (int npcIndex)
 
static void TransformElderSlime (int npcIndex)
 
static int TypeToDefaultHeadIndex (int type)
 
static void UnlockOrExchangePet (ref bool petBoughtFlag, int npcType, string textKeyForLicense, int netMessageData)
 
static void UpdateFoundActiveNPCs ()
 
static void UpdateRGBPeriheralProbe ()
 
static bool WouldBeEncouragedToDespawn (int aistyle, int type)
 
- Static Public Member Functions inherited from Entity
static IEntitySource GetSource_NaturalSpawn ()
 
static ? IEntitySource GetSource_None ()
 
static IEntitySource GetSource_TownSpawn ()
 
static ? IEntitySource InheritSource (Entity entity)
 

Public Attributes

float[] ai = new float[maxAI]
 An array with 4 slots used for any sort of data storage, which is occasionally synced from the server to clients. Each vanilla NPCAIStyleID uses these slots for different purposes. Set netUpdate to true to manually sync. The advantage of using these 4 floats is that they are synced automatically. Using fields in your ModNPC class will work just the same, but they might need to be synced via ModNPC.SendExtraAI(System.IO.BinaryWriter) and ModNPC.ReceiveExtraAI(System.IO.BinaryReader) if necessary.
Clever use of Reference return valuesas seen in ExampleCustomAISlimeNPC.cscan be used to reuse the ai array entries with readable names.
Defaults to the values passed into NPC.NewNPC(IEntitySource, int, int, int, int, float, float, float, float, int), usually [0, 0, 0, 0].
 
int aiAction
 
int aiStyle
 Selects which vanilla code to use for the AI method. Vanilla NPC AI styles are enumerated in the NPCAIStyleID class. Modders can use vanilla aiStyle and optionally ModNPC.AIType to mimic AI code already in the game. This is usually only useful as a prototyping tool since it is difficult to customize existing aiStyle code. See ModNPC.AIType and PartyZombieto see how to use vanilla ai. If you are using custom AI code, there is no need to set this field. Customizing an existing aiStyle usually requires following the Vanilla Code Adaption Guide. An aiStyle of 0 will face the player automatically, while an aiStyle of -1 is used for completely custom ai. Defaults to 0 for vanilla NPC and -1 for modded NPC.
 
int alpha
 0 is opaque, and 255 is transparent. Note that this is the opposite of how alpha is typically expressed in computer graphics. Can be used to fade an NPC in and out.
Use Opacity instead for a 0f to 1f scaling that uses the high value for fully opaque, as is more typical in computer graphics.
Defaults to 0.
 
int altTexture
 
bool behindTiles
 Indicates that this NPC draws behind solid tiles.
See ExampleDrawBehindNPCfor examples of how to use this and other options for layers to draw in.
 
bool betsysCurse
 
bool bloodButchered
 
bool boss
 Set to true if the NPC is a boss. Prevents off-screen despawn. Bosses also need [AutoloadBossHead] annotated on the ModNPC class itself to fully register as a boss.
 
int breath
 
int breathCounter
 
bool[] buffImmune = new bool[BuffLoader.BuffCount]
 Contains the NPC buff immunities for this NPC. The default values in this array are populated from NPCID.Sets.ImmuneToAllBuffs, NPCID.Sets.ImmuneToRegularBuffs, NPCID.Sets.SpecificDebuffImmunity, and BuffID.Sets.GrantImmunityWith.
 
int[] buffTime = new int[maxBuffs]
 
int[] buffType = new int[maxBuffs]
 
bool CanBeReplacedByOtherNPCs
 
bool canDisplayBuffs = true
 
bool canGhostHeal = true
 
int catchItem
 The numerical ID of the item that this NPC becomes when caught.
Mainly used for critters that can be caught with bug nets, such as butterflies and worms.
Bug nets and other catching tools will only work on NPCs with this field set to something greater than 0.
 
bool celled
 
bool chaseable = true
 If false, this NPC will be ignored by CanBeChasedBy, meaning that entities won't specifically target this NPC. The cultists set this to true, helping ensure that they are not accidentally killed by minions or homing weapons. Duke Fishron uses this during his 3rd phase while he is invisible, resulting in homing weapons and minions being unable to target him effectively. Defaults to true.
 
bool closeDoor
 
bool coldDamage
 Denotes whether or not this NPC counts as dealing cold damage for the purposes of the Warmth Potion.
Defaults to false.
 
bool collideX
 
bool collideY
 
Color color
 
bool confused
 
int damage
 The amount of contact damage this NPC deals.
Changing this WILL NOT change the amount of damage done by projectiles.
Usually damage is scaled by some factor when NPC spawn projectiles with Projectile.NewProjectile in AI code. For example, passing in (int)(NPC.damage * 0.5f) as the Damage parameter.
The List of NPCs wiki pagecan be useful for finding appropriate values.
 
bool daybreak
 
SoundStyleDeathSound
 The sound that plays when this npc dies. Set this to an existing SoundID entry or assign to a new SoundStyle for a custom sound.
The Basic Sounds Guideteaches how to find existing sounds to use, how to use custom sounds, and how to customize the playback properties of the sounds.
For example NPC.DeathSound = SoundID.NPCDeath1; can be used for the typical NPC kill sound.
Defaults to null.
 
int defDamage
 Stores the value of damage at the end of SetDefaults. Useful for scaling damage in AI code conditionally.
 
int defDefense
 Stores the value of defense at the end of SetDefaults. Useful for scaling defense in AI code, like how King Slime changes defense as it gets smaller.
 
int defense
 How resistant to damage this NPC is.
The List of NPCs wiki pagecan be useful for finding appropriate values.
 
bool despawnEncouraged
 
int directionY = 1
 
bool dontCountMe
 
bool dontTakeDamage
 Indicates that this NPC does not currently take damage, attacks won't hit it. Some example usage includes Blazing Wheel, Spike Ball, Golem Head during 2nd phase, Jellyfish while electrified, and Granite Golem while shielding. Defaults to false.
 
bool dontTakeDamageFromHostiles
 
int doorX
 
int doorY
 
bool dripping
 
bool drippingSlime
 
bool drippingSparkleSlime
 
bool dryadBane
 
bool dryadWard
 
int extraValue
 
bool ForcePartyHatOn
 
Rectangle frame
 The portion ("frame") of this NPC's spritesheet that will be drawn. ModNPC should adjust this in ModNPC.FindFrame(int).
 
double frameCounter
 
bool friendly
 Indicates that an NPC is friendly to players. If true, a player won't damage the NPC and the NPC won't deal contact damage to players, unless otherwise forced.
Mostly set to true for town npc and rescuable town npc.
Naturally spawned critter NPC that are Main.npcCatchable will automatically be friendly for 1.5 seconds after spawning.

 
int friendlyRegen
 
float gfxOffY
 An offset from the actual position of the npc that will be added to the draw position. Used to fake the effect of NPC smoothly traveling up single block obstacles.
 
bool GravityIgnoresLiquid = false
 Set to disable the effect of being submerged in liquid on NPC gravity.
Note that being submerged in liquid overrides both type and space effects.
 
bool GravityIgnoresSpace = false
 Set to disable the effect of being in space on NPC gravity.
 
bool GravityIgnoresType = false
 Set to disable vanilla type and AI based NPC gravity calculations.
Affects types 258, 425, 576, 577, 427, 426, 541, and the aiStyle 7.
Use with caution
 
MultipliableFloat GravityMultiplier = MultipliableFloat.One
 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.
 
bool hide
 Indicates that this NPC is drawn at a specific layer in the render order. Must use in conjunction with ModNPC.DrawBehind(int).
See ExampleDrawBehindNPCfor examples of how to use this and all available layers to draw in.
 
SoundStyleHitSound
 The sound that plays when this npc is hit. Set this to an existing SoundID entry or assign to a new SoundStyle for a custom sound.
The Basic Sounds Guideteaches how to find existing sounds to use, how to use custom sounds, and how to customize the playback properties of the sounds.
For example NPC.HitSound = SoundID.NPCHit1; can be used for the typical NPC hit sound.
Defaults to null.
 
bool homeless
 
int homeTileX = -1
 
int homeTileY = -1
 
float honeyMovementSpeed = 0.25f
 
int housingCategory
 
bool ichor
 
bool immortal
 Indicates that damage dealt to this NPC will not cause its life to go down. It can still receive hits and damage numbers will be shown, but the damage will not be applied to life. Only used by NPCID.TargetDummy. Defaults to false.
 
int[] immune = new int[256]
 This determines if an NPC can be hit by a item or projectile owned by a particular player (it is an array, each slot corresponds to different players (whoAmI)). It is decremented towards 0 every update. Melee items set immune[Player.whoAmI] to Player.itemAnimation, which starts at item.useAnimation and decrements towards 0. Penetrating projectiles usually set immune to 10, while non-penetrating projectiles do not set immune. ExamplePiercingProjectile.csexplains more about options for npc and projectile immunity.
 
bool IsABestiaryIconDummy
 
bool javelined
 
bool justHit
 
float knockBackResist = 1f
 How much of the knockback it receives will actually apply. 1f: full knockback; 0f: no knockback.
Defaults to 1f.
 
int lastInteraction = 255
 The Entity.whoAmI of the Player that last damaged this NPC. Used to award Banner items to the player that killed the NPC, but can be used for many other effects.

The default value is 255. If the value is 255, the NPC has not been damaged by any Player.

The playerInteraction array tracks all players that have damaged this NPC.
 
int lastPortalColorIndex
 
bool lavaImmune
 
float lavaMovementSpeed = 0.5f
 
int life
 The current life of the NPC. Automatically set to the value of lifeMax at the end of SetDefaults.
 
int lifeMax
 The maximum life of this NPC.
 
int lifeRegen
 The rate of this player's life regeneration or loss in health per tick, divided by 120. To put it another way, it is health regeneration every 2 seconds. Used to implement the damage over time of debuffs.
For example, subtracting 12 from this value loses 12 / 120 = 1/10 health per tick, or 6 health per second.
Life regeneration is accumulated every tick in lifeRegenCount.
This value should be subtracted from in ModNPC.UpdateLifeRegen(ref int) or GlobalNPC.UpdateLifeRegen(NPC, ref int). See DamageOverTimeGlobalNPC.csfor an example. The game does not actually use positive life regen for NPC, so positive values might not work as expected.
 
int lifeRegenCount
 This NPC's accumulated life regeneration.
If this value reaches or exceeds 120, the NPC gains lifeRegenCount / 120 health and this value decreases until it no longer exceeds 120.
If this value reaches or exceeds -120, the NPC loses health in the same way.
In either case, text will appear above the NPC indicating the life regeneration or life loss.
 
int lifeRegenExpectedLossPerSecond = -1
 
float[] localAI = new float[maxAI]
 Acts like ai, but does not sync to the server. Many vanilla NPCAIStyleID use these slots for various purposes.
Defaults to [0, 0, 0, 0]
 
bool loveStruck
 
bool markedByScytheWhip
 
MultipliableFloat MaxFallSpeedMultiplier = MultipliableFloat.One
 Multiply this value in order to change the NPCs active maxFallSpeed, this can be done in AI as gravity values are reset slightly beforehand
 
bool midas
 
float nameOver
 
bool netAlways
 
int netID
 Similar to type, but accounts for negative NPCID values.



 
Vector2 netOffset = Vector2.Zero
 
int netSkip
 
int netSpam
 
bool netUpdate
 Set to true in ModNPC.AI or other suitable places to trigger the NPC syncing code (MessageID.SyncNPC). This will sync position, life, and other data about this NPC from the server to the clients. Modded data from ModNPC.SendExtraAI(System.IO.BinaryWriter) and GlobalNPC.SendExtraAI(NPC, ModLoader.IO.BitWriter, System.IO.BinaryWriter) will be included. Use this to sync changes so that the client's NPC instances stay in sync with the server's. Only changes that are non-Deterministic on the client's side, such as random decisions or code only running on the server, need to be synced. The Basic Netcode wiki pagegoes into more details and links to examples. As the server is in charge of NPC, changes to NPC data should only happen on the server in multiplayer.
 
bool netUpdate2
 
bool noGravity
 If true, the npc will not be affected by gravity. Demon Eyes and other floating npc use this.
Defaults to false.
 
bool noTileCollide
 If true, the npc does not collide with tiles, making the npc pass through tiles freely. Meteor Head and Worm npc use this.
Defaults to false.
 
float npcSlots = 1f
 Represents how much this npc counts towards the npc spawn limit. Small critters like worms or flies have values around 0.1f and 0.25f. Enemies that are more difficult than normal have values higher than 1f, and bosses and mini bosses have values around 6.
Proper npcSlots values help balance the game and prevents the player from randomly being overwhelmed by powerful enemies. The Spawn rates section on the NPC spawning wiki pagelists vanilla npcSlots values. Use this as a guide to find a suitable value.
Defaults to 1f.
 
bool oiled
 
int oldDirectionY
 
bool oldHomeless
 
int oldHomeTileX = -1
 
int oldHomeTileY = -1
 
Vector2[] oldPos = new Vector2[10]
 
float[] oldRot = new float[10]
 
int oldTarget
 
bool onFire
 
bool onFire2
 
bool onFire3
 
bool onFrostBurn
 
bool onFrostBurn2
 
bool[] playerInteraction = new bool[256]
 Tracks which Players have damaged this NPC. Damaging boss minions or other parts of a boss is usually counted as damaging the main body of the boss. Used to determine which players participated in a boss fight and should receive a boss bag.

Indexed by each players Entity.whoAmI (or Main.myPlayer for code running locally).

lastInteraction tracks which player was the last player to damage this NPC. AnyInteractions can be used to easily check if any player has damaged the NPC.
 
bool poisoned
 
int rarity
 How rare the NPC is for the Lifeform Analyzer. For example: 4 is for Tim and Mimics, 1 is for bound town NPCs.
Defaults to 0.
 
int realLife = -1
 Stores the index (the Entity.whoAmI) of a single NPC. This NPC will then share a health pool with that NPC.
Used for the Destroyer's various segments and the Wall of Flesh's eyes and mouth.
This is useful for worm enemies. All the segments will point to the same npc, usually the "head" of the npc, and the head and all other non-multi-part NPCs will have the default value of -1 still.
Defaults to -1.
 
bool reflectsProjectiles
 
short releaseOwner = 255
 Identifies the player who released this NPC into the world. Used mainly for released critters. Helps limit how many critters a player can release. Default to 255, indicating that the npc was not released by a player.
 
float rotation
 
float scale = 1f
 Makes the NPC bigger or smaller. Bigger than 1f is bigger.
Defaults to 1f.
 
bool setFrameSize
 
bool shadowFlame
 
bool shimmering
 
float shimmerMovementSpeed = 0.375f
 
float shimmerTransparency
 
bool soulDrain
 
int soundDelay
 
bool SpawnedFromStatue
 Indicates that this NPC was spawned by a statue. Mainly affects item drops. Prevents item drops in pre-hardmode if NPCID.Sets.NoEarlymodeLootWhenSpawnedFromStatue is true. Also prevents item drops if NPCID.Sets.StatueSpawnedDropRarity isn't -1 and either a random value is higher than that chance or the npc was not damaged by a player. Prevents NPC.CatchNPC(int, int). Defaults to false.
 
int spriteDirection = -1
 
bool stairFall
 
int statsAreScaledForThisManyPlayers
 
float stepSpeed
 Has nothing to do with the speed that this NPC travels, that is dictated by AI code adjusting Entity.velocity. This affects how quickly gfxOffY is adjusted.
 
bool stinky
 
float strengthMultiplier = 1f
 
float takenDamageMultiplier = 1f
 
int target = -1
 The Player that this NPC is currently targeting, represented as the index of that Player within Main.player (the Player's Entity.whoAmI). This is typically set by calling the NPC.TargetClosest(bool) method. Use HasValidTarget to check if target has a valid value before accessing Main.player[NPC.target] and doing logic dealing with the targeted player. Defaults to -1. Some NPC support targeting other NPC (SupportsNPCTargets). For these NPC, target will be set to a value between 300 and 500. See HasNPCTarget, TranslatedTargetIndex, and NPCID.Sets.UsesNewTargetting for more information on that feature.
 
Rectangle targetRect
 
bool teleporting
 
int teleportStyle
 
float teleportTime
 
bool tentacleSpiked
 
int timeLeft
 Despawn timer in charge of determining when an NPC that is offscreen but not far away enough to immediately despawn will despawn naturally. Gets set to activeTime when near any player and decreases each update otherwise. The NPC despawning wiki pagehas more information. ModNPC.CheckActive can be used to prevent an NPC outside the immediate despawn range from despawning. More...
 
bool townNPC
 
int townNpcVariationIndex
 
bool trapImmune
 
int type
 The NPC ID of this NPC. The NPC ID is a unique number assigned to each NPC loaded into the game. This will be equal to either an NPCID entry or ModContent.NPCType<T>, for example NPCID.AngryBones or ModContent.NPCType<MyModNPC>(). To check if an NPC instance is a specific NPC, check NPC.type == NPCID.VanillaNPCHere or NPC.type == ModContent.NPCType<ModdedNPCHere>() in an if statement.

More...
 
float value
 How many copper coins the NPC will drop when killed (100 copper coins = 1 silver coin etc.).
 
bool venom
 
float waterMovementSpeed = 0.5f
 
- Public Attributes inherited from Entity
bool active
 If true, the Entity actually exists within the game world. Within the specific entity array, if active is false, the entity is junk data. Always check active if iterating over the entity array. Another option for iterating is to use Main.ActivePlayers, Main.ActiveNPCs, Main.ActiveProjectiles, or Main.ActiveItems instead for simpler code.
 
int direction = 1
 The direction this entity is facing. A value of 1 means the entity is facing to the right. -1 means facing to the left.
 
int height
 The height of this Entity's hitbox, in pixels.
 
bool honeyWet
 
bool lavaWet
 
int oldDirection
 The direction of this Entity during the previous tick. For projectiles with Projectile.extraUpdates, this will be the direction during the previous extra update, not necessarily the direction during the previous tick.
 
Vector2 oldPosition
 The position of this Entity during the previous tick. For projectiles with Projectile.extraUpdates, this will be the position during the previous extra update, not necessarily the position during the previous tick.
 
Vector2 oldVelocity
 The velocity of this Entity during the previous tick. For projectiles with Projectile.extraUpdates, this will be the velocity during the previous extra update, not necessarily the velocity during the previous tick.
 
Vector2 position
 The position of this Entity in world coordinates. Note that this corresponds to the top left corner of the entity. Use Center instead for logic that needs the position at the center of the entity.
 
bool shimmerWet
 
Vector2 velocity
 The velocity of this Entity in world coordinates per tick.
 
bool wet
 The Entity is currently in water.
Projectile: Affects movement speed and some projectiles die when wet. Projectile.ignoreWater prevents this.
 
byte wetCount
 
int whoAmI
 The index of this Entity within its specific array. These arrays track the entities in the world.
Item: unused
Projectile: Main.projectile
NPC: Main.npc
Player: Main.player Note that Projectile.whoAmI is not consistent between clients in multiplayer for the same projectile.
 
int width
 The width of this Entity's hitbox, in pixels.
 

Static Public Attributes

static int activeTime = 750
 Default despawn time. Set to 750 or 12.5 seconds. Use to update timeLeft when the NPC is close to any player.
 
static readonly int AFKTimeNeededForNoWorms = 300
 
static bool boughtBunny = false
 
static bool boughtCat = false
 
static bool boughtDog = false
 
static int brainOfGravity = -1
 
const int breathMax = 200
 
static int butterflyChance = 0
 
static int[,] cavernMonsterType = new int[2, 3]
 
static bool combatBookVolumeTwoWasUsed = false
 
static bool combatBookWasUsed = false
 Denotes whether or not Advanced Combat Techniques has been used in the current world.
 
static int crimsonBoss = -1
 
static int deerclopsBoss = -1
 
static bool downedAncientCultist = false
 Denotes whether or not the Lunatic Cultist has been defeated at least once in the current world.
 
static bool downedBoss1 = false
 Denotes whether or not the Eye of Cthulhu has been defeated at least once in the current world.
 
static bool downedBoss2 = false
 Denotes whether or not the Eater of Worlds OR the Brain of Cthulhu have been defeated at least once in the current world.
This does NOT track the two of them separately; you will need to establish your own fields in a ModSystem for that.

 
static bool downedBoss3 = false
 Denotes whether or not Skeletron has been defeated at least once in the current world.
 
static bool downedChristmasIceQueen = false
 Denotes whether or not at least one Ice Queen has been defeated in the current world.
 
static bool downedChristmasSantank = false
 Denotes whether or not at least one Santa-NK1 has been defeated in the current world.
 
static bool downedChristmasTree = false
 Denotes whether or not at least one Everscream has been defeated in the current world.
 
static bool downedClown = false
 Denotes whether or not at least one Clown has been killed in the current world.
Only used to make the Clothier sell the Clown set once at least one has been killed.
 
static bool downedDeerclops = false
 Denotes whether or not the Deerclops has been defeated at least once in the current world.
 
static bool downedEmpressOfLight = false
 Denotes whether or not the Empress of Light has been defeated at least once in the current world.
 
static bool downedFishron = false
 Denotes whether or not Duke Fishron has been defeated at least once in the current world.
 
static bool downedFrost = false
 Denotes whether or not the Frost Legion has been defeated at least once in the current world.
 
static bool downedGoblins = false
 Denotes whether or not at least one Goblin Army has been defeated in the current world.
 
static bool downedGolemBoss = false
 Denotes whether or not Golem has been defeated at least once in the current world.
 
static bool downedHalloweenKing = false
 Denotes whether or not at least one Pumpking has been defeated in the current world.
 
static bool downedHalloweenTree = false
 Denotes whether or not at least one Mourning Wood has been defeated in the current world.
 
static bool downedMartians = false
 Denotes whether or not at least one Martian Madness event has been cleared in the current world.
 
static bool downedMechBoss1 = false
 Denotes whether or not the Destroyer has been defeated at least once in the current world.
 
static bool downedMechBoss2 = false
 Denotes whether or not the Twins have been defeated at least once in the current world.
 
static bool downedMechBoss3 = false
 Denotes whether or not Skeletron Prime has been defeated at least once in the current world.
 
static bool downedMechBossAny = false
 Denotes whether or not ANY Mechanical Boss has been defeated at least once in the current world.
 
static bool downedMoonlord = false
 Denotes whether or not the Moon Lord has been defeated at least once in the current world.
 
static bool downedPirates = false
 Denotes whether or not at least one Pirate Invasion has been defeated in the current world.
 
static bool downedPlantBoss = false
 Denotes whether or not Plantera has been defeated at least once in the current world.
 
static bool downedQueenBee = false
 Denotes whether or not at least one Queen Bee has been defeated in the current world.
 
static bool downedQueenSlime = false
 Denotes whether or not Queen Slime has been defeated at least once in the current world.
 
static bool downedSlimeKing = false
 Denotes whether or not King Slime has been defeated at least once in the current world.
 
static bool downedTowerNebula = false
 Denotes whether or not the Nebula Pillar has been defeated at least once in the current world.
 
static bool downedTowerSolar = false
 Denotes whether or not the Solar Pillar has been defeated at least once in the current world.
 
static bool downedTowerStardust = false
 Denotes whether or not the Stardust Pillar has been defeated at least once in the current world.
 
static bool downedTowerVortex = false
 Denotes whether or not the Vortex Pillar has been defeated at least once in the current world.
 
static bool empressRageMode = false
 
static bool fairyLog = false
 
static int fireFlyChance = 0
 
static int fireFlyFriendly = 0
 
static int fireFlyMultiple = 0
 
static bool freeCake = false
 
static int goldCritterChance = 400
 
static int golemBoss = -1
 
static int immuneTime = 20
 
const int ItemMoonlordCountdownTime = 720
 
static int[] killCount = new int[NPCID.Count]
 
static int ladyBugBadLuckTime = -10800
 
static int ladyBugGoodLuckTime = 43200
 
static int[] lazyNPCOwnedProjectileSearchArray = new int[200]
 
static bool LunarApocalypseIsUp = false
 
static int LunarShieldPowerMax = 100
 
static int LunarShieldPowerNormal = 100
 
static int maxAI = 4
 
static readonly int maxBuffs = 20
 
static int MaxMoonLordCountdown = 3600
 
static int mechQueen = -1
 
static int[] MoonEventRequiredPointsPerWaveLookup
 
static readonly int[,,,] MoonLordAttacksArray = InitializeMoonLordAttacks()
 
static readonly int[,] MoonLordAttacksArray2 = InitializeMoonLordAttacks2()
 
static int MoonLordCountdown = 0
 
static int MoonLordFightingDistance = 4500
 
const float nameOverDistance = 350f
 
const float nameOverIncrement = 0.025f
 
const int NaturalMoonlordCountdownTime = 3600
 
static bool[] npcsFoundForCheckActive = new bool[NPCID.Count]
 
static int offSetDelayTime = 60
 
static bool peddlersSatchelWasUsed = false
 
static int plantBoss = -1
 
static bool PreventJojaColaDialog = false
 
static int RerollDryadText = 0
 
static CoinLossRevengeSystem RevengeManager = new CoinLossRevengeSystem()
 
static int safeRangeX = (int)((double)(sWidth / 16) * 0.52)
 
static int safeRangeY = (int)((double)(sHeight / 16) * 0.52)
 
static bool savedAngler = false
 
static bool savedBartender = false
 
static bool savedGoblin = false
 
static bool savedGolfer = false
 
static bool savedMech = false
 
static bool savedStylist = false
 
static bool savedTaxCollector = false
 
static bool savedWizard = false
 
static int sHeight = 1080
 
static int ShieldStrengthTowerNebula = 0
 
static int ShieldStrengthTowerSolar = 0
 
static int ShieldStrengthTowerStardust = 0
 
static int ShieldStrengthTowerVortex = 0
 
static bool[] ShimmeredTownNPCs = new bool[NPCID.Count]
 
static int stinkBugChance = 0
 
static int sWidth = 1920
 
static bool taxCollector = false
 
static float totalInvasionPoints = 0f
 
static bool TowerActiveNebula = false
 
static bool TowerActiveSolar = false
 
static bool TowerActiveStardust = false
 
static bool TowerActiveVortex = false
 
static bool travelNPC = false
 
static bool unlockedArmsDealerSpawn = false
 
static bool unlockedDemolitionistSpawn = false
 
static bool unlockedDyeTraderSpawn = false
 
static bool unlockedMerchantSpawn = false
 
static bool unlockedNurseSpawn = false
 
static bool unlockedPartyGirlSpawn = false
 
static bool unlockedPrincessSpawn = false
 
static bool unlockedSlimeBlueSpawn = false
 
static bool unlockedSlimeCopperSpawn = false
 
static bool unlockedSlimeGreenSpawn = false
 
static bool unlockedSlimeOldSpawn = false
 
static bool unlockedSlimePurpleSpawn = false
 
static bool unlockedSlimeRainbowSpawn = false
 
static bool unlockedSlimeRedSpawn = false
 
static bool unlockedSlimeYellowSpawn = false
 
static bool unlockedTruffleSpawn = false
 
static float waveKills = 0f
 
static int waveNumber = 0
 

Properties

IBigProgressBar BossBar [get, set]
 Assign a special boss bar, vanilla or modded. Not used by vanilla. More...
 
bool CanBeTalkedTo [get]
 
bool CanTalk [get]
 
bool CountsAsACritter [get]
 
static bool downedTowers [get]
 
RefReadOnlyArray< GlobalNPCEntityGlobals [get]
 
string FullName [get]
 The FULL name of this NPC.
If the NPC doesn't have a given name, this will just return the type name. A Stylist without a given name will always return "Stylist" here.
If the NPC does have a given name, this will return the NPC's full name; given name first, then type name.
Full name with a given name is given in the format of "X the Y", where X is their given name and Y is their type name.
For example, a Stylist might return "Scarlett the Stylist" here; with Scarlett being her given name, and Stylist being her type name.

 
string GivenName [get, set]
 The GIVEN name of this NPC. Can be set directly.
Given names are unique to each NPC, though two NPCs can have the same given name.
Some vanilla examples of given names are Andrew (for the Guide), Yorai (for the Princess), Whitney (for the Steampunker), or Scarlett (for the Stylist).

 
string GivenOrTypeName [get]
 If this NPC has a given name, returns their given name; otherwise, returns their type name.

 
EntityGlobalsEnumerator< GlobalNPCGlobals [get]
 
float gravity [get]
 The current change in velocity due to gravity applied every frame.
Multiply GravityMultiplier to modify this value
 
static float[] GravityWetMultipliers = new float[4] { 2f / 3f, 2f / 3f, 1f / 3f, 1.5f / 3f } [get]
 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.
 
NPCHappiness Happiness [get]
 Provides access to (static) happiness data associated with this NPC's type.
 
bool HasGivenName [get]
 Whether or not this NPC has a given name.

 
bool HasNPCTarget [get]
 
bool HasPlayerTarget [get]
 
bool HasValidTarget [get]
 Checks if target is a valid Player to target. This checks that target has a valid value and that the specified Player is alive, active, not a ghost. If this NPC supports targeting other NPC (SupportsNPCTargets), then this will check if that NPC is still active.
 
bool HideStrikeDamage [get, set]
 If true, damage combat text will not be shown by StrikeNPC(HitInfo, bool, bool) and dps meter will not record damage against this NPC.
Recommended for use with NPC.immortal
 
bool isLikeATownNPC [get]
 Returns true if either NPCID.Sets.ActsLikeTownNPC or townNPC is true.
 
static bool IsMechQueenUp [get]
 
bool IsShimmerVariant [get]
 
float maxFallSpeed [get]
 The current fall speed cap in velocity applied every frame.
Multiply MaxFallSpeedMultiplier to modify this value
 
static float[] MaxFallSpeedWetMultipliers = new float[4] { 0.7f, 0.7f, 0.4f, 0.55f } [get]
 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.
 
ModNPC ModNPC [get, set]
 
float Opacity [get, set]
 The transparency of the NPC expressed as a float value from 0f (transparent) to 1f (opaque). This property wraps alpha.
 
static int ShieldStrengthTowerMax [get]
 
bool ShowNameOnHover [get, set]
 
bool SuperArmor [get, set]
 Helper property for defense >= 9999. Extremely high defense is interpreted as 'super armor' where attacks will only do 1 damage (or 2 for crits), no matter how strong they are.
Passed to HitModifiers.SuperArmor when doing damage calculations. See the docs there for more info.
The only way to bypass super armor is to call StrikeNPC(HitInfo, bool, bool), or set NPC life directly.
 
bool SupportsNPCTargets [get]
 Shorthand for checking NPCID.Sets.UsesNewTargetting.
 
static bool TooWindyForButterflies [get]
 
static bool TowersDefeated [get]
 
int TranslatedTargetIndex [get]
 
string TypeName [get]
 The TYPE name of this NPC.
Type names are the base titles given to any NPC, and are typically shared amongst all instances of an NPC. For example, the Stylist's type name will always be "Stylist".
To modify the type name of a specific NPC, make use of the ModifyTypeName hooks in GlobalNPC and ModLoader.ModNPC, according to your needs.

 
int WhoAmIToTargettingIndex [get]
 
- Properties inherited from Entity
Vector2 Bottom [get, set]
 
Vector2 BottomLeft [get, set]
 
Vector2 BottomRight [get, set]
 
Vector2 Center [get, set]
 The center position of this entity in world coordinates. Calculated from position, width, and height.
 
Rectangle Hitbox [get, set]
 
Vector2 Left [get, set]
 
Vector2 Right [get, set]
 
Vector2 Size [get, set]
 
Vector2 Top [get, set]
 
Vector2 TopLeft [get, set]
 
Vector2 TopRight [get, set]
 
virtual Vector2 VisualPosition [get]
 
- Properties inherited from IEntityWithGlobals< GlobalNPC >
RefReadOnlyArray< TGlobal > EntityGlobals [get]
 
int Type [get]
 

Member Function Documentation

◆ AddBuff()

void NPC.AddBuff ( int  type,
int  time,
bool  quiet = false 
)

Gives this NPC the provided buff. This accounts for if the NPC is immune to the buff.
If the NPC already has the buff, the re-apply logic will happen. Vanilla buff types are found in BuffID and modded buffs are typically retrieved using ModContent.BuffType<T>.
The quiet parameter will determine if the network sync message should happen. This should always stay false.

Parameters
typeThe buff type
timeThe desired buff time in ticks. 60 ticks is 1 second
quietIf true, the network sync message is skipped.

◆ AnyInteractions()

bool NPC.AnyInteractions ( )

Returns true if any player has damaged this NPC. Individual player participation can be determined by checking playerInteraction directly. Use GetWereThereAnyInteractions if realLife might be in use.

Returns

◆ AnyNPCs()

static bool NPC.AnyNPCs ( int  Type)
static

Returns true if there are any active NPC in the world of the given NPC type (NPC.type).

Parameters
Type
Returns

◆ BecomeImmuneTo()

void NPC.BecomeImmuneTo ( int  buffType)

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 BuffID.Sets.GrantImmunityWith). This method can be followed by ClearImmuneToBuffs(out bool) if the NPC should clear any buff it currently has that it is now immune to.

Parameters
buffType

◆ CalculateHitInfo()

HitInfo NPC.CalculateHitInfo ( int  damage,
int  hitDirection,
bool  crit = false,
float  knockBack = 0f,
DamageClass  damageType = null,
bool  damageVariation = false,
float  luck = 0 
)

Runs NPCLoader.ModifyIncomingHit hooks and and does the full damage calculations.
The result HitInfo.Damage will contain the health the NPC will lose when applied.

Parameters
damageThe damage to deal to the NPC, before modifications, defense, resistances etc
hitDirectionThe hit direction of the resulting strike (1 or -1)
critDefaults to false
knockBackDefaults to 0
damageTypeDefaults to DamageClass.Default
damageVariationWhether to apply damage variation. Defaults to false.
luckLuck modifier to produce weight damageVariation towards higher (positive) or lower (negative) values. Defaults to 0
Returns
A HitInfo for use with StrikeNPC(HitInfo, bool, bool) and NetMessage.SendStrikeNPC

◆ CanBeChasedBy()

bool NPC.CanBeChasedBy ( object  attacker = null,
bool  ignoreDontTakeDamage = false 
)

Returns true if this NPC should be considered an enemy to attack. Used by various player, projectile, mount, and town npc logic. For example homing projectiles like Chlorophyte bullet won't target friendly NPC, critters, or NPC that are currently flagged as invulnerable. Note that the attacker parameter is unused. The logic checks that the NPC meets all of the following criteria: Entity.active, chaseable, lifeMax > 5 (to ignore critters), dontTakeDamage (unless ignoreDontTakeDamage ) is true), not friendly, and not immortal.

Parameters
attacker
ignoreDontTakeDamage
Returns

◆ CheckCatchNPC()

static bool NPC.CheckCatchNPC ( NPC  npc,
Rectangle  catchToolRectangle,
Item  item,
Player  player,
bool  lavaProofTool = false 
)
static

Runs most code related to the process of checking whether or not an NPC can be caught.
After that, CombinedHooks.OnCatchNPC is run, followed by the code responsible for catching the NPC if applicable.
You will need to call this manually if you want to make an NPC-catching tool which acts differently from vanilla's, such as one that uses a projectile instead of an item.
As a note, if calling this manually, you will need to check npc.active && npc.catchItem > 0 yourself.

Parameters
npcThe NPC which can potentially be caught.
catchToolRectangleThe hitbox of the tool being used to catch the NPC — be it an item, a projectile, or something else entirely.
itemThe item to be used as a reference for the purposes of CombinedHooks.CanCatchNPC and CombinedHooks.OnCatchNPC.
playerThe player that owns the referenced item.
lavaProofToolWhether or not the tool is lavaproof for the purposes of catching vanilla's Underworld critters. Defaults to false.
Returns
Whether or not the NPC was successfully caught.

◆ ClearImmuneToBuffs()

void NPC.ClearImmuneToBuffs ( out bool  anyBuffsCleared)

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(int).

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.

Parameters
anyBuffsCleared

◆ CountNPCS()

static int NPC.CountNPCS ( int  Type)
static

Returns the number of active NPC in the world of the given NPC type (NPC.type).

Parameters
Type
Returns

◆ DelBuff()

void NPC.DelBuff ( int  buffIndex)

Removes the buff at the provided index and shuffles the remaining buff indexes down to fill the gap. The buff types and times will then be synced to clients. This method should only be called on the server or in single player.

Parameters
buffIndexThe index of the buff to remove.

◆ FindFirstNPC()

static int NPC.FindFirstNPC ( int  Type)
static

Returns the index within Main.npc of the the first active NPC in the world of the given NPC type (NPC.type).

Parameters
Type
Returns

◆ GetFirstNPCNameOrNull()

static string NPC.GetFirstNPCNameOrNull ( int  npcType)
static

Returns the GivenOrTypeName of the first active NPC of the given type in the world. If not found, null is returned.

Parameters
npcType
Returns

◆ GetFullnameByID()

static string NPC.GetFullnameByID ( int  npcID)
static

Returns the FullName of the first active NPC of the given type in the world. If not found, the type name is returned instead.

Parameters
npcID
Returns

◆ GetGlobalNPC< T >() [1/2]

T NPC.GetGlobalNPC< T > ( )

Gets the instance of the specified GlobalNPC type. This will throw exceptions on failure.

Exceptions
KeyNotFoundException
Exceptions
IndexOutOfRangeException
Type Constraints
T :GlobalNPC 
T :GlobalNPC.GetGlobal<T> 
T :type 
T :EntityGlobals 

◆ GetGlobalNPC< T >() [2/2]

T NPC.GetGlobalNPC< T > ( baseInstance)

Gets the local instance of the type of the specified GlobalNPC instance. This will throw exceptions on failure.

Exceptions
KeyNotFoundException
Exceptions
NullReferenceException
Type Constraints
T :GlobalNPC 
T :GlobalNPC.GetGlobal 
T :type 
T :EntityGlobals 
T :baseInstance 

◆ GetIncomingStrikeModifiers()

HitModifiers NPC.GetIncomingStrikeModifiers ( DamageClass  damageType,
int  hitDirection,
bool  ignoreArmorDebuffs = false 
)

Initializes a HitModifiers calculation with the properties of this NPC, including calling NPCLoader.ModifyIncomingHit

Parameters
damageTypeThe DamageType of the hit.
hitDirectionThe direction to apply knockback. If 0, no knockback will be applied.
ignoreArmorDebuffsIgnores ichor and betsysCurse. Only used for legacy vanilla codepaths.
Returns

◆ GetNPCInvasionGroup()

static int NPC.GetNPCInvasionGroup ( int  npcID)
static

Gets the InvasionID associated with the given NPC type (NPC.type).

Parameters
npcIDThe NPC type to check.
Returns
0 for NPCs not affiliated with any invasion.
A positive InvasionID for NPCs affiliated with standard events, such as the Goblin Army.
A negative InvasionID for NPCs affiliated with a wave-based event, such as the Pumpkin Moon. Wave-based events are prefixed with "Cached" in InvasionID.

◆ GetPartyHatGore()

int NPC.GetPartyHatGore ( )

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.

Returns

◆ GetWereThereAnyInteractions()

bool NPC.GetWereThereAnyInteractions ( )

Returns true if any player has damaged this NPC. Individual player participation can be determined by checking playerInteraction directly.

Returns

◆ HasBuff< T >()

bool NPC.HasBuff< T > ( )

Type Constraints
T :ModBuff 
T :HasBuff 
T :ModContent.BuffType<T>() 

◆ NewNPC()

static int NPC.NewNPC ( IEntitySource  source,
int  X,
int  Y,
int  Type,
int  Start = 0,
float  ai0 = 0f,
float  ai1 = 0f,
float  ai2 = 0f,
float  ai3 = 0f,
int  Target = 255 
)
static

Spawns an NPC into the game world with the given type.
This method should not be called on multiplayer clients.
The X and Y parameters dictate the centered spawn position.
>ai0, ai1, ai2, ai3 will initialize the NPC.ai[] array with the supplied values. This can be used to pass in information to the NPC. The NPC AI code will have to be written to utilize those values.

Parameters
source
X
Y
TypeEither an NPCID entry or ModContent.NPCType<T>, for example NPCID.BabySlime or ModContent.NPCType<MyModNPC>()
StartThe lowest slot in which this NPC can spawn. This can be used to ensure that the spawned NPC draws behind an existing NPC. This is useful for bosses that spawn minions.
ai0
ai1
ai2
ai3
TargetOptionally, provide a Player.whoAmI to set NPC.target to a specific Player immediately on spawn.
Returns
The index of the spawned NPC within the Main.npc array

◆ NewNPCDirect() [1/2]

static NPC NPC.NewNPCDirect ( IEntitySource  source,
int  x,
int  y,
int  type,
int  start = 0,
float  ai0 = 0f,
float  ai1 = 0f,
float  ai2 = 0f,
float  ai3 = 0f,
int  target = 255 
)
static



This particular overload returns the actual NPC instance rather than the index of the spawned NPC within the Main.npc array.
A short-hand for

Main.npc[NPC.NewNPC(...)]

◆ NewNPCDirect() [2/2]

static NPC NPC.NewNPCDirect ( IEntitySource  source,
Vector2  position,
int  type,
int  start = 0,
float  ai0 = 0f,
float  ai1 = 0f,
float  ai2 = 0f,
float  ai3 = 0f,
int  target = 255 
)
static



This particular overload returns the actual NPC instance rather than the index of the spawned NPC within the Main.npc array. It also uses a Vector2 for the spawn position instead of X and Y.
A short-hand for

Main.npc[NPC.NewNPC(...)]

◆ RequestBuffRemoval()

void NPC.RequestBuffRemoval ( int  buffTypeToRemove)

Removes the buff type and shuffles the remaining buff indexes down to fill the gap. Note that only buffs contained in BuffID.Sets.CanBeRemovedByNetMessage can be removed with this method. The intention is that those specific buffs are "owned" by the player who inflicts them, so they can be freely removed by multiplayer clients.

In all other cases code running on the server or in single player is in charge of the NPC debuffs and NPC.DelBuff should be used directly.

Parameters
buffTypeToRemoveThe buff type

◆ SimpleStrikeNPC()

int NPC.SimpleStrikeNPC ( int  damage,
int  hitDirection,
bool  crit = false,
float  knockBack = 0f,
DamageClass  damageType = null,
bool  damageVariation = false,
float  luck = 0,
bool  noPlayerInteraction = false 
)

Calls CalculateHitInfo, StrikeNPC(HitInfo, bool, bool) and then NetMessage.SendStrikeNPC (in multiplayer)

Parameters
damageThe damage to deal to the NPC, before modifications, defense, resistances etc
hitDirectionThe hit direction of the resulting strike (1 or -1)
critDefaults to false
knockBackDefaults to 0
damageTypeDefaults to DamageClass.Default
damageVariationWhether to apply damage variation. Defaults to false.
luckLuck modifier to produce weight damageVariation towards higher (positive) or lower (negative) values. Defaults to 0
noPlayerInteractionPrevents PlayerInteraction(int) from being called in single player. In multiplayer, player interaction is handled by the server.
Returns
The actual health lost by the NPC. Normally this is HitInfo.Damage but it is capped at the current health of the NPC, and represents the actual damage dealt in the case of HitInfo.InstantKill

◆ StrikeNPC()

int NPC.StrikeNPC ( HitInfo  hit,
bool  fromNet = false,
bool  noPlayerInteraction = false 
)

Directly deals damage to the NPC, spawns combat text, plays hit sound, deals knockback based on the provided HitInfo
Calls HitEffect(HitInfo) and associated hooks after dealing damage.
Calls checkDead
Does not automatically send packets. Use NetMessage.SendStrikeNPC to synchronize hits.

Parameters
hitThe parameters of the hit. Normally obtained via NPC.HitModifiers or CalculateHitInfo
fromNettrue if this strike came from another client over the network. Just changes the combat text to be darker in color.
noPlayerInteractionPrevents PlayerInteraction(int) from being called in single player. In multiplayer, player interaction is handled by the server.
Returns
The actual health lost by the NPC. Normally this is HitInfo.Damage but it is capped at the current health of the NPC, and represents the actual damage dealt in the case of HitInfo.InstantKill

◆ TargetClosest()

void NPC.TargetClosest ( bool  faceTarget = true)

Targets the closest alive Player and optionally faces towards that Player. This will set target to the targeted player, as well as Entity.direction if faceTarget is true. Make sure to check HasValidTarget before accessing target.

Parameters
faceTarget

◆ TryGetGlobalNPC< T >() [1/2]

bool NPC.TryGetGlobalNPC< T > ( out T  result)

Gets the instance of the specified GlobalNPC type.

Type Constraints
T :GlobalNPC 
T :GlobalNPC.TryGetGlobal 
T :type 
T :EntityGlobals 
T :out 
T :result 

◆ TryGetGlobalNPC< T >() [2/2]

bool NPC.TryGetGlobalNPC< T > ( baseInstance,
out T  result 
)

Safely attempts to get the local instance of the type of the specified GlobalNPC instance.

Returns
Whether or not the requested instance has been found.
Type Constraints
T :GlobalNPC 
T :GlobalNPC.TryGetGlobal 
T :type 
T :EntityGlobals 
T :baseInstance 
T :out 
T :result 

Member Data Documentation

◆ MoonEventRequiredPointsPerWaveLookup

int [] NPC.MoonEventRequiredPointsPerWaveLookup
static
Initial value:
= new int[21] {
0,
25,
40,
50,
80,
100,
160,
180,
200,
250,
300,
375,
450,
525,
675,
850,
1025,
1325,
1550,
2000,
0
}

◆ timeLeft

int NPC.timeLeft

Despawn timer in charge of determining when an NPC that is offscreen but not far away enough to immediately despawn will despawn naturally. Gets set to activeTime when near any player and decreases each update otherwise. The NPC despawning wiki pagehas more information. ModNPC.CheckActive can be used to prevent an NPC outside the immediate despawn range from despawning.


◆ type

int NPC.type

The NPC ID of this NPC. The NPC ID is a unique number assigned to each NPC loaded into the game. This will be equal to either an NPCID entry or ModContent.NPCType<T>, for example NPCID.AngryBones or ModContent.NPCType<MyModNPC>(). To check if an NPC instance is a specific NPC, check NPC.type == NPCID.VanillaNPCHere or NPC.type == ModContent.NPCType<ModdedNPCHere>() in an if statement.

<negativenote>There are a few NPC that share the same type number, usually slight variations of enemies. NPCID.GreenSlime and NPCID.RedSlime have values of -3 and -8, respectively, but after they are spawned they will have the type equal to 1, which is the same value as NPCID.BlueSlime. If code logic requires differentiating between these variations, use netID instead.</negativenote>

Property Documentation

◆ BossBar

IBigProgressBar NPC.BossBar
getset

Assign a special boss bar, vanilla or modded. Not used by vanilla.

To assign a modded boss bar, use NPC.BossBar = ModContent.GetInstance<ExampleBossBar>(); 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