• For issues you find with the Switch and Console releases, please follow this link and give as much detail as possible. This is the speediest way to get info to Pipeworks and get a hotfix in the works.
  • 1.4 will bring many changes to the PC version. We strongly advise making plans to back up your worlds and players prior to updating your game. More details here.
  • Begin your search for Journey's End information here and here. Please report bugs and issues for Journey's End here.
  • For issues you find with the Mobile 1.3 update, please follow this link and give as much detail as possible. This is the speediest way to get info to DR Studios to look at your issue. Also, some troubleshooting hints here.

tModLoader Official tModLoader Help Thread

NameTaken

Skeletron
The player has a velocity variable, so in the swords code you could override ModifyHitNPC and do this code:
C#:
public override void ModifyHitNPC (Player player, NPC target, ref int damage, ref float knockBack, ref bool crit)
{
    // Multiply the damage of the sword by 3x when the players velocity is above 1.2f
    if (player.velocity > 1.2f)
    {
        damage *= 3;
    }
}
You can change the 1.2f to whatever
im curious, could you make it increase mana cost for a weapon? Could you increase knockback?Could you make a weapon only usable while motionless?
 

sparks08

Skeletron
I'm trying to make a projectile that does lifesteal, but it says no suitable method found to override, if I remove the player player and the statlife line it works fine and the projectile inflicts ichor, but how can i make it do lifesteal as well?

Code:
  public override void OnHitNPC(Player Player, NPC target, int damage, float knockBack, bool crit)
        {
            Player.statLife += damage / 100;
            target.AddBuff(BuffID.Ichor, 1000);
        }
The "no suitable method found to override" happened to me to when I added player to any overrides. Simply change 'Override' to 'Virtual'.
So Instead of this:
Code:
  public override void OnHitNPC(Player Player, NPC target, int damage, float knockBack, bool crit)
        {
            Player.statLife += damage / 100;
            target.AddBuff(BuffID.Ichor, 1000);
        }
It is now this:
Code:
  public virtual void OnHitNPC(Player Player, NPC target, int damage, float knockBack, bool crit)
        {
            Player.statLife += damage / 100;
            target.AddBuff(BuffID.Ichor, 1000);
        }
Alternatively / If that doesn't work, you can establish Player as the owner of the projectile: Player player = Main.player[projectile.owner];

So It would be like this:
Code:
  public override void OnHitNPC(NPC target, int damage, float knockBack, bool crit)
        {
            Player player = Main.player[projectile.owner];
            Player.statLife += damage / 100;
            target.AddBuff(BuffID.Ichor, 1000);
        }
Hope that helps! :)
 
Last edited:

sparks08

Skeletron

adsfghg

Terrarian
The "no suitable method found to override" happened to me to when I added player to any overrides. Simply change 'Override' to 'Virtual'.
So Instead of this:
Code:
  public override void OnHitNPC(Player Player, NPC target, int damage, float knockBack, bool crit)
        {
            Player.statLife += damage / 100;
            target.AddBuff(BuffID.Ichor, 1000);
        }
It is now this:
Code:
  public virtual void OnHitNPC(Player Player, NPC target, int damage, float knockBack, bool crit)
        {
            Player.statLife += damage / 100;
            target.AddBuff(BuffID.Ichor, 1000);
        }
Alternatively / If that doesn't work, you can establish Player as the owner of the projectile: Player player = Main.player[projectile.owner];

So It would be like this:
Code:
  public override void OnHitNPC(NPC target, int damage, float knockBack, bool crit)
        {
            Player player = Main.player[projectile.owner];
            Player.statLife += damage / 100;
            target.AddBuff(BuffID.Ichor, 1000);
        }
Hope that helps! :)
Tysm it worked!
now the next thing I'm trying to make is an accessory that gives life steal on all your damages when equipped, like the spectre hood set bonus, but I want it to work on all damage types and I want to customize the percentage of lifesteal, I tried ghostheal but idk if there are any ways to modify it so it works with all damage types and different lifesteal percentage?
part of code:
Code:
  public override void UpdateAccessory(Player player, bool hideVisual)
        {
            player.statLifeMax2 += 100;
            player.statManaMax += 100;
            player.allDamage += 2;
            player.lifeRegen += 0;
            player.lifeSteal += 9999999999999;
            player.AddBuff(Terraria.ID.BuffID.Ichor, 1);
            player.ghostHeal = true;
            player.ghostDmg = 999f;
        }
 

eutyjdghfja5

Terrarian
*** edit *** I fixed it by switching the stage it uses to "tunnels" *** edit ***
*** edit edit *** this means it doesn't crash, but it has no effect on the world *** edit edit ***
*** edit edit edit *** I've got the tile generation to work, but not detecting the size of the world or creating air blocks *** edit edit edit ***

I'm createing a terrain generator to replace the "terrain" step in world generation.

I get this error when I try to generate a new world:
Code:
[17:15:51] [8/INFO] [StatusText]: Resetting game objects
[17:15:52] [8/INFO] [Terraria]: Generating World: 3
[17:15:52] [8/WARN] [tML]: Silently Caught Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
   at Terraria.WorldGen.<>c.<generateWorld>b__260_2(GenerationProgress <p0>)
   at Terraria.GameContent.Generation.PassLegacy.Apply(GenerationProgress progress)
   at Terraria.World.Generation.WorldGenerator.GenerateWorld(GenerationProgress progress)
   at Terraria.WorldGen.generateWorld(Int32 seed, GenerationProgress customProgressObject)
   at Terraria.WorldGen.do_worldGenCallBack(Object threadContext)
   at Terraria.WorldGen.worldGenCallBack(Object threadContext)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

[17:15:52] [8/ERROR] [tML]: A problem was encountered during world generation
Tunnels
System.NullReferenceException: Object reference not set to an instance of an object.
   at Terraria.WorldGen.<>c.<generateWorld>b__260_2(GenerationProgress <p0>)
   at Terraria.GameContent.Generation.PassLegacy.Apply(GenerationProgress progress)
   at Terraria.World.Generation.WorldGenerator.GenerateWorld(GenerationProgress progress)
[17:15:52] [8/ERROR] [Terraria]: A problem was encountered during world generation
System.NullReferenceException: Object reference not set to an instance of an object.
   at Terraria.World.Generation.WorldGenerator.GenerateWorld(GenerationProgress progress)
   at Terraria.WorldGen.generateWorld(Int32 seed, GenerationProgress customProgressObject)
   at Terraria.WorldGen.do_worldGenCallBack(Object threadContext)
   at Terraria.WorldGen.worldGenCallBack(Object threadContext)
[17:16:47] [1/DEBUG] [tML]: Process.Start (UseShellExecute = True): "C:\Users\jaspe\Documents\My Games\Terraria\ModLoader\Logs\client.log"
My code looks like this:

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.World.Generation;
using Microsoft.Xna.Framework;
using Terraria.GameContent.Generation;
using Terraria.Map;
using On.Terraria.IO;
using System.Security.Cryptography.X509Certificates;

namespace JasperMod.worldgen
{
    class worldgen2 : ModWorld
    {
        private const int saveVersion = 0;
        public override void ModifyWorldGenTasks(List<GenPass> tasks, ref float totalWeight)
        {
            int TerrainGen = tasks.FindIndex(genpass => genpass.Name.Equals("Tunnels"));
            tasks[TerrainGen] = new PassLegacy("My Terrain", delegate (GenerationProgress progress) {
                int seed = 10; //Main.ActiveWorldFileData.Seed;
                Random randomNumber = new System.Random(seed.GetHashCode());

                int GridWidth = 4200; //Main.ActiveWorldFileData.WorldSizeX;
                int GridHeight = 1200; //Main.ActiveWorldFileData.WorldSizeY;

                float angleVariation = 10f;
                double height;
                double lastHeight = GridHeight / 2;
                double gradient = 0;
                double randomChange;
                
                for (int x = 1; x < GridWidth; x++)
                {
                    randomChange = randomNumber.Next((int)(-angleVariation * 5), (int)((angleVariation * 5) + 1)) / 10;
                    gradient += randomChange;
                    if (gradient > 10 || gradient < -10)
                    {
                        gradient -= randomChange;
                    }
                    height = gradient + lastHeight;
                    if (height < 5) { gradient += 1; }
                    if (height < 1) { height = 1; gradient = 1; }
                    if (height > GridHeight - 12) { gradient -= 1; }
                    if (height > GridHeight) { height = GridHeight; gradient = -1; }

                    for (int y = 1; y < (int)height; y++)
                    {
                        if (y <= (int)height)
                        {
                            if (y <= (int)height - 10) // block
                            { WorldGen.TileRunner(x, (y * -1) + GridHeight, 2, 3, TileID.Titanium, true); }
                            else
                            { WorldGen.TileRunner(x, (y * -1) + GridHeight, 2, 3, TileID.Adamantite, true); }
                        }
                        else
                        {
                            WorldUtils.ClearTile(x, (y * -1) + GridHeight, false); // air
                        }
                    }
                }
            });
        }
    }
}
 
Last edited:

NameTaken

Skeletron
anybody know how to make a stackable boomerang? also, is there a way to make it do extra damage if you have a full stack?
 

TheGodlyPiggy

Terrarian
Ok so i want to make an equipment that will heal you for a tenth of the damage dealt. Here's the code:

Code:
     public override void OnHitNPC(Player player, int damage, float knockback, bool crit)
        {
              int amountToHeal = damage / 10; // Heal tenth of damage
                if(amountToHeal + player.statLife > player.statLifeMax2)
                    amountToHeal = player.statLifeMax2 - player.statLife; // If healing is larger than health currently missing.
                player.statLife += amountToHeal;
        }
It keeps saying that there was no suitable methods to override... Anyone knows how to fix it?
[edit]: When i remove override there's no compiling error but doesn't run the code or something... I really should take C# classes lol
 

TakenSmile

Terrarian
I was wondering on how to make a custom NPC inflict a custom buff. I'm making an acid biome and I already made a debuff that makes you lose health and I already have a couple NPCs for the biome so I'm wondering what I can do that makes the NPCs inflict the debuff on contact.
 

adsfghg

Terrarian
Ok so i want to make an equipment that will heal you for a tenth of the damage dealt. Here's the code:

Code:
     public override void OnHitNPC(Player player, int damage, float knockback, bool crit)
        {
              int amountToHeal = damage / 10; // Heal tenth of damage
                if(amountToHeal + player.statLife > player.statLifeMax2)
                    amountToHeal = player.statLifeMax2 - player.statLife; // If healing is larger than health currently missing.
                player.statLife += amountToHeal;
        }
It keeps saying that there was no suitable methods to override... Anyone knows how to fix it?
[edit]: When i remove override there's no compiling error but doesn't run the code or something... I really should take C# classes lol
I had this issue before and someone helped me on that, change ur code to :
Code:
 public override void OnHitNPC(NPC target, int damage, float knockback, bool crit)
        {
              Player player = Main.player[projectile.owner];
              int amountToHeal = damage / 10; // Heal tenth of damage
                if(amountToHeal + player.statLife > player.statLifeMax2)
                    amountToHeal = player.statLifeMax2 - player.statLife; // If healing is larger than health currently missing.
                player.statLife += amountToHeal;
        }
 

Will-Banksy

Skeletron Prime
Ok so i want to make an equipment that will heal you for a tenth of the damage dealt. Here's the code:

Code:
     public override void OnHitNPC(Player player, int damage, float knockback, bool crit)
        {
              int amountToHeal = damage / 10; // Heal tenth of damage
                if(amountToHeal + player.statLife > player.statLifeMax2)
                    amountToHeal = player.statLifeMax2 - player.statLife; // If healing is larger than health currently missing.
                player.statLife += amountToHeal;
        }
It keeps saying that there was no suitable methods to override... Anyone knows how to fix it?
[edit]: When i remove override there's no compiling error but doesn't run the code or something... I really should take C# classes lol
You forgot a parameter - Try this:

C#:
public override void OnHitNPC(Player player, NPC target, int damage, float knockBack, bool crit)
Unless you want to create your own method, you need to override the methods defined in your classes superclass. I would advise you to have at least a quick look at C# tutorials online, this might be useful: C# Tutorial - Tutorialspoint
 

Will-Banksy

Skeletron Prime
anybody know how to make a stackable boomerang? also, is there a way to make it do extra damage if you have a full stack?
In SetDefaults for your item, set item.maxStack to the desired size. As for scaling the damage, I don't know how you'd do that so it changes the item.damage when the stack size changes, but in Shoot(...) you can get the current stack size with item.stack and scale the damage of the fired projectile accordingly
 

jonahr

Terrarian
My town NPC is not spawning(I am a beginner btw so it might be a rookie mistake). Do you know how I could fix it? How could I just make it spawn when I join the world? Thank you and here is the code.
Code:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria.ID;
using Terraria;
using Terraria.ModLoader;

namespace Firstmod.Items.NPCs          //We need thiFs to basically indicate the folder where it is to be read from, so you the texture will load correctly
{
    public class PlagueDoctor : ModNPC
    {
        public override bool Autoload(ref string name)
        {
            name = "PlagueDoctor";
            return mod.Properties.Autoload;
        }

        public override void SetDefaults()
        {
            npc.townNPC = true; //This defines if the npc is a town Npc or not
            npc.friendly = true;  //this defines if the npc can hur you or not()
            npc.width = 18; //the npc sprite width
            npc.height = 46;  //the npc sprite height
            npc.aiStyle = 7; //this is the npc ai style, 7 is Pasive Ai
            npc.defense = 25;  //the npc defense
            npc.lifeMax = 250;// the npc life
            npc.HitSound = SoundID.NPCHit1;  //the npc sound when is hit
            npc.DeathSound = SoundID.NPCDeath1;  //the npc sound when he dies
            npc.knockBackResist = 0.5f;  //the npc knockback resistance
            Main.npcFrameCount[npc.type] = 6; //this defines how many frames the npc sprite sheet has
            NPCID.Sets.ExtraFramesCount[npc.type] = 0;
            NPCID.Sets.AttackFrameCount[npc.type] = 0;
            NPCID.Sets.DangerDetectRange[npc.type] = 150; //this defines the npc danger detect range
            NPCID.Sets.AttackType[npc.type] = 1; //this is the attack type,  0 (throwing), 1 (shooting), or 2 (magic). 3 (melee)
            NPCID.Sets.AttackTime[npc.type] = 30; //this defines the npc attack speed
            NPCID.Sets.AttackAverageChance[npc.type] = 10;//this defines the npc atack chance
            NPCID.Sets.HatOffsetY[npc.type] = 4; //this defines the party hat position
            animationType = NPCID.Guide;  //this copy the cyborg animation
        }
        public override string TownNPCName()     //Allows you to give this town NPC any name when it spawns
        {
            switch (WorldGen.genRand.Next(1))
            {
                case 0:
                    return "The Plague Doctor";
                default:
                    return "The PLague Doctor";
            }
        }

        public override void SetChatButtons(ref string button, ref string button2)  //Allows you to set the text for the buttons that appear on this town NPC's chat window.
        {
            button = "Buy Potions";   //this defines the buy button name
        }
        public override void OnChatButtonClicked(bool firstButton, ref bool openShop) //Allows you to make something happen whenever a button is clicked on this town NPC's chat window. The firstButton parameter tells whether the first button or second button (button and button2 from SetChatButtons) was clicked. Set the shop parameter to true to open this NPC's shop.
        {

            if (firstButton)
            {
                openShop = true;   //so when you click on buy button opens the shop
            }
        }

        public override void SetupShop(Chest shop, ref int nextSlot)       //Allows you to add items to this town NPC's shop. Add an item by setting the defaults of shop.item[nextSlot] then incrementing nextSlot.
        {
            if (NPC.downedMechBossAny)   //this make so when the king slime is killed the town npc will sell this
            {
                shop.item[nextSlot].SetDefaults(ItemID.GreaterHealingPotion);  //an example of how to add a vanilla terraria item
                nextSlot++;
                shop.item[nextSlot].SetDefaults(ItemID.GreaterManaPotion);
                nextSlot++;
            }
            if (NPC.downedQueenBee)   //this make so when Skeletron is killed the town npc will sell this
            {
                shop.item[nextSlot].SetDefaults(ItemID.HealingPotion);
                nextSlot++;
                shop.item[nextSlot].SetDefaults(ItemID.ManaPotion);
                nextSlot++;
            }
            shop.item[nextSlot].SetDefaults(ItemID.LesserHealingPotion);
            nextSlot++;
            shop.item[nextSlot].SetDefaults(mod.ItemType("Thechefknife"));  //this is an example of how to add a modded item
            nextSlot++;

        }

        public override string GetChat()       //Allows you to give this town NPC a chat message when a player talks to it.
        {
            switch (Main.rand.Next(4))    //this are the messages when you talk to the npc
            {
                case 0:
                    return "Ah, please keep your distance";
                case 1:
                    return "Medical school..? I beg your pardon?";
                case 2:
                    return "Please refrain from touching.";
                case 3:
                    return "That modern nurse has no respect for my practices.";
                default:
                    return "We'll settle this later.";

            }
        }
        public override void TownNPCAttackStrength(ref int damage, ref float knockback)//  Allows you to determine the damage and knockback of this town NPC attack
        {
            damage = 40;  //npc damage
            knockback = 2f;   //npc knockback
        }

        public override void TownNPCAttackCooldown(ref int cooldown, ref int randExtraCooldown)  //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.
        {
            cooldown = 5;
            randExtraCooldown = 10;
        }
        //------------------------------------This is an example of how to make the npc use a sward attack-------------------------------
        public override void DrawTownAttackSwing(ref Texture2D item, ref int itemSize, ref float scale, ref Vector2 offset)//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 of 3). Item is the Texture2D instance of the item to be drawn (use Main.itemTexture[id of item]), itemSize is the width and height of the item's hitbox
        {
            scale = 1f;
            item = Main.itemTexture[mod.ItemType("TheSpatula")]; //this defines the item that this npc will use
            itemSize = 56;
        }

        public override void TownNPCAttackSwing(ref int itemWidth, ref int itemHeight) //  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.
        {
            itemWidth = 56;
            itemHeight = 56;
        }

        //----------------------------------This is an example of how to make the npc use a gun and a projectile ----------------------------------
        /*public override void DrawTownAttackGun(ref float scale, ref int item, ref int closeness) //Allows you to customize how this town NPC's weapon is drawn when this NPC is shooting (this NPC must have an attack type of 1). Scale is a multiplier for the item's drawing size, item is the ID of the item to be drawn, and closeness is how close the item should be drawn to the NPC.
          {
              scale = 1f;
              item = mod.ItemType("GunName");
              closeness = 20;
          }
          public override void TownNPCAttackProj(ref int projType, ref int attackDelay)//Allows you to determine the projectile type of this town NPC's attack, and how long it takes for the projectile to actually appear
          {
              projType = ProjectileID.CrystalBullet;
              attackDelay = 1;
          }

          public override void TownNPCAttackProjSpeed(ref float multiplier, ref float gravityCorrection, ref float randomOffset)//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
          {
              multiplier = 7f;
             // randomOffset = 4f;

          }   */

    }
}
 

NameTaken

Skeletron
In SetDefaults for your item, set item.maxStack to the desired size. As for scaling the damage, I don't know how you'd do that so it changes the item.damage when the stack size changes, but in Shoot(...) you can get the current stack size with item.stack and scale the damage of the fired projectile accordingly
Okay, thanks for the help!
 

sparks08

Skeletron
My town NPC is not spawning(I am a beginner btw so it might be a rookie mistake). Do you know how I could fix it? How could I just make it spawn when I join the world? Thank you and here is the code.
Code:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria.ID;
using Terraria;
using Terraria.ModLoader;

namespace Firstmod.Items.NPCs          //We need thiFs to basically indicate the folder where it is to be read from, so you the texture will load correctly
{
    public class PlagueDoctor : ModNPC
    {
        public override bool Autoload(ref string name)
        {
            name = "PlagueDoctor";
            return mod.Properties.Autoload;
        }

        public override void SetDefaults()
        {
            npc.townNPC = true; //This defines if the npc is a town Npc or not
            npc.friendly = true;  //this defines if the npc can hur you or not()
            npc.width = 18; //the npc sprite width
            npc.height = 46;  //the npc sprite height
            npc.aiStyle = 7; //this is the npc ai style, 7 is Pasive Ai
            npc.defense = 25;  //the npc defense
            npc.lifeMax = 250;// the npc life
            npc.HitSound = SoundID.NPCHit1;  //the npc sound when is hit
            npc.DeathSound = SoundID.NPCDeath1;  //the npc sound when he dies
            npc.knockBackResist = 0.5f;  //the npc knockback resistance
            Main.npcFrameCount[npc.type] = 6; //this defines how many frames the npc sprite sheet has
            NPCID.Sets.ExtraFramesCount[npc.type] = 0;
            NPCID.Sets.AttackFrameCount[npc.type] = 0;
            NPCID.Sets.DangerDetectRange[npc.type] = 150; //this defines the npc danger detect range
            NPCID.Sets.AttackType[npc.type] = 1; //this is the attack type,  0 (throwing), 1 (shooting), or 2 (magic). 3 (melee)
            NPCID.Sets.AttackTime[npc.type] = 30; //this defines the npc attack speed
            NPCID.Sets.AttackAverageChance[npc.type] = 10;//this defines the npc atack chance
            NPCID.Sets.HatOffsetY[npc.type] = 4; //this defines the party hat position
            animationType = NPCID.Guide;  //this copy the cyborg animation
        }
        public override string TownNPCName()     //Allows you to give this town NPC any name when it spawns
        {
            switch (WorldGen.genRand.Next(1))
            {
                case 0:
                    return "The Plague Doctor";
                default:
                    return "The PLague Doctor";
            }
        }

        public override void SetChatButtons(ref string button, ref string button2)  //Allows you to set the text for the buttons that appear on this town NPC's chat window.
        {
            button = "Buy Potions";   //this defines the buy button name
        }
        public override void OnChatButtonClicked(bool firstButton, ref bool openShop) //Allows you to make something happen whenever a button is clicked on this town NPC's chat window. The firstButton parameter tells whether the first button or second button (button and button2 from SetChatButtons) was clicked. Set the shop parameter to true to open this NPC's shop.
        {

            if (firstButton)
            {
                openShop = true;   //so when you click on buy button opens the shop
            }
        }

        public override void SetupShop(Chest shop, ref int nextSlot)       //Allows you to add items to this town NPC's shop. Add an item by setting the defaults of shop.item[nextSlot] then incrementing nextSlot.
        {
            if (NPC.downedMechBossAny)   //this make so when the king slime is killed the town npc will sell this
            {
                shop.item[nextSlot].SetDefaults(ItemID.GreaterHealingPotion);  //an example of how to add a vanilla terraria item
                nextSlot++;
                shop.item[nextSlot].SetDefaults(ItemID.GreaterManaPotion);
                nextSlot++;
            }
            if (NPC.downedQueenBee)   //this make so when Skeletron is killed the town npc will sell this
            {
                shop.item[nextSlot].SetDefaults(ItemID.HealingPotion);
                nextSlot++;
                shop.item[nextSlot].SetDefaults(ItemID.ManaPotion);
                nextSlot++;
            }
            shop.item[nextSlot].SetDefaults(ItemID.LesserHealingPotion);
            nextSlot++;
            shop.item[nextSlot].SetDefaults(mod.ItemType("Thechefknife"));  //this is an example of how to add a modded item
            nextSlot++;

        }

        public override string GetChat()       //Allows you to give this town NPC a chat message when a player talks to it.
        {
            switch (Main.rand.Next(4))    //this are the messages when you talk to the npc
            {
                case 0:
                    return "Ah, please keep your distance";
                case 1:
                    return "Medical school..? I beg your pardon?";
                case 2:
                    return "Please refrain from touching.";
                case 3:
                    return "That modern nurse has no respect for my practices.";
                default:
                    return "We'll settle this later.";

            }
        }
        public override void TownNPCAttackStrength(ref int damage, ref float knockback)//  Allows you to determine the damage and knockback of this town NPC attack
        {
            damage = 40;  //npc damage
            knockback = 2f;   //npc knockback
        }

        public override void TownNPCAttackCooldown(ref int cooldown, ref int randExtraCooldown)  //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.
        {
            cooldown = 5;
            randExtraCooldown = 10;
        }
        //------------------------------------This is an example of how to make the npc use a sward attack-------------------------------
        public override void DrawTownAttackSwing(ref Texture2D item, ref int itemSize, ref float scale, ref Vector2 offset)//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 of 3). Item is the Texture2D instance of the item to be drawn (use Main.itemTexture[id of item]), itemSize is the width and height of the item's hitbox
        {
            scale = 1f;
            item = Main.itemTexture[mod.ItemType("TheSpatula")]; //this defines the item that this npc will use
            itemSize = 56;
        }

        public override void TownNPCAttackSwing(ref int itemWidth, ref int itemHeight) //  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.
        {
            itemWidth = 56;
            itemHeight = 56;
        }

        //----------------------------------This is an example of how to make the npc use a gun and a projectile ----------------------------------
        /*public override void DrawTownAttackGun(ref float scale, ref int item, ref int closeness) //Allows you to customize how this town NPC's weapon is drawn when this NPC is shooting (this NPC must have an attack type of 1). Scale is a multiplier for the item's drawing size, item is the ID of the item to be drawn, and closeness is how close the item should be drawn to the NPC.
          {
              scale = 1f;
              item = mod.ItemType("GunName");
              closeness = 20;
          }
          public override void TownNPCAttackProj(ref int projType, ref int attackDelay)//Allows you to determine the projectile type of this town NPC's attack, and how long it takes for the projectile to actually appear
          {
              projType = ProjectileID.CrystalBullet;
              attackDelay = 1;
          }

          public override void TownNPCAttackProjSpeed(ref float multiplier, ref float gravityCorrection, ref float randomOffset)//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
          {
              multiplier = 7f;
             // randomOffset = 4f;

          }   */

    }
}
It seems like you are missing this line of code:
C#:
        public override bool CanTownNPCSpawn(int numTownNPCs, int money) {
            for (int k = 0; k < 255; k++) {
                Player player = Main.player[k];
                if (!player.active) {
                    continue;
                }
            //Attach other code here
            }
            return false;
        }
Continue makes it so if player is active, the code continues, but I am not an expert, remember that.
Return false makes it so the town NPC will not spawn if conditions are not met.
Always make it false if you want it to only spawn when conditions are met.
Returning it true will make it always spawn.

Other code:
This line of code makes it so that a town npc can only spawn if the player has something in their inventory
C#:
                foreach (Item item in player.inventory) {
                    if (item.type == Number) {
                        return true;
                    }
                }
            }
            return false;
        }
        }
Replace number with an item ID, from looking at your level of coding, I suppose you know where the Item values are.

This line of code makes it so that a town npc can only spawn if the player has defeated a boss.
C#:
                if (NPC.downedBoss) {
                    return true;
                }
                return false;
            }
            return false;
        }
        }
downedBoss1 (Eye of Cthulhu)
downedBoss2 (Eater of Worlds)
downedBoss3 (Skeletron)
Add Mech at the end for the mechanical versions of these bosses (Although there may be a chance they are swapped)
downedQueenBee (Queen Bee)
downedSlimeKing (King Slime)
There are way more, Here is the full list
One more thing, code paths:
This code is incorrect:
C#:
                if (Something) {
                    return true;
                }
            }
            return false;
        }
        }
However, this code IS correct:
C#:
                if (Something) {
                    return true;
                }
                return false;
            }
            return false;
        }
        }
This is a thing called code paths.
On the first example, the system read that there has to be something to return true. But doesn't know what would happen if something doesn't happen, so it would be an error. So, by adding return false a line after "}" will make it so the system knows that if something doesn't happen, it returns false.
There we go! Hope it helps! :)
 
Last edited:

TheGodlyPiggy

Terrarian
"Error: C:\Users\Utilisateur\Documents\My Games\Terraria\ModLoader\Mod Sources\DepressionCollection\Items\Accessories\VampireCharm.cs(37,21) : error CS0136: A local or parameter named 'player' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter"

halp

Code:

C#:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using DepressionCollection.Tiles;
using DepressionCollection.Projectiles;
using Terraria.ID;
using Terraria;
using Terraria.ModLoader;
using static Terraria.ModLoader.ModContent;
using Terraria.Utilities;

namespace DepressionCollection.Items.Accessories
{
    public class VampireCharm: ModItem
    {
        public override void SetStaticDefaults()
        {
            Tooltip.SetDefault("'Will heal you a tenth of damage dealt'");
        }

        public override void SetDefaults()
        {
            item.width = 20;
            item.height = 20;
            item.accessory = true;
            item.value = Item.sellPrice(silver: 30);
            item.rare = ItemRarityID.Blue;
        }

        public override int ChoosePrefix(UnifiedRandom rand)
        {
            return rand.Next(new int[] { PrefixID.Arcane, PrefixID.Lucky, PrefixID.Menacing, PrefixID.Quick, PrefixID.Violent, PrefixID.Warding });
        }

        public override void OnHitNPC(Player player, NPC target, int damage, float knockBack, bool crit)
        {
              Player player = Main.player[projectile.owner];
              int amountToHeal = damage / 10; // Heal tenth of damage
                if(amountToHeal + player.statLife > player.statLifeMax2)
                    amountToHeal = player.statLifeMax2 - player.statLife; // If healing is larger than health currently missing.
                player.statLife += amountToHeal;
        }

        public override void AddRecipes()
        {
            ModRecipe recipe = new ModRecipe(mod);
            recipe.AddIngredient(ItemID.DirtBlock, 2);
            recipe.AddTile(TileID.Anvils);
            recipe.SetResult(this);
            recipe.AddRecipe();
        }
    }
}
 

jonahr

Terrarian
I am trying to make my town NPC spawn after the Wall of Flesh has been defeated, but I do not see it on the list.How would I do that?
 

sparks08

Skeletron
"Error: C:\Users\Utilisateur\Documents\My Games\Terraria\ModLoader\Mod Sources\DepressionCollection\Items\Accessories\VampireCharm.cs(37,21) : error CS0136: A local or parameter named 'player' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter"

halp

Code:

C#:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using DepressionCollection.Tiles;
using DepressionCollection.Projectiles;
using Terraria.ID;
using Terraria;
using Terraria.ModLoader;
using static Terraria.ModLoader.ModContent;
using Terraria.Utilities;

namespace DepressionCollection.Items.Accessories
{
    public class VampireCharm: ModItem
    {
        public override void SetStaticDefaults()
        {
            Tooltip.SetDefault("'Will heal you a tenth of damage dealt'");
        }

        public override void SetDefaults()
        {
            item.width = 20;
            item.height = 20;
            item.accessory = true;
            item.value = Item.sellPrice(silver: 30);
            item.rare = ItemRarityID.Blue;
        }

        public override int ChoosePrefix(UnifiedRandom rand)
        {
            return rand.Next(new int[] { PrefixID.Arcane, PrefixID.Lucky, PrefixID.Menacing, PrefixID.Quick, PrefixID.Violent, PrefixID.Warding });
        }

        public override void OnHitNPC(Player player, NPC target, int damage, float knockBack, bool crit)
        {
              Player player = Main.player[projectile.owner];
              int amountToHeal = damage / 10; // Heal tenth of damage
                if(amountToHeal + player.statLife > player.statLifeMax2)
                    amountToHeal = player.statLifeMax2 - player.statLife; // If healing is larger than health currently missing.
                player.statLife += amountToHeal;
        }

        public override void AddRecipes()
        {
            ModRecipe recipe = new ModRecipe(mod);
            recipe.AddIngredient(ItemID.DirtBlock, 2);
            recipe.AddTile(TileID.Anvils);
            recipe.SetResult(this);
            recipe.AddRecipe();
        }
    }
}
public override void OnHitNPC already has a definition for player:
public override void OnHitNPC(Player player, NPC target, int damage, float knockBack, bool crit)
That means you don't need to declare Player player again.
 
Top Bottom