2025 tModLoader API 开发者教程
全面的 API 教程,涵盖 ModItem、ModNPC 和高级开发技术,附带实际示例。
核心 API 类概览
ModItem
创建自定义武器、工具、配件和消耗品
- • SetDefaults() - Define item properties
- • AddRecipes() - Create crafting recipes
- • UseItem() - Custom use behavior
ModNPC
创建敌人、城镇 NPC 和具有自定义 AI 的 Boss
- • SetDefaults() - NPC stats and behavior
- • AI() - Custom artificial intelligence
- • ModifyNPCLoot() - Define drop tables
示例:创建高级魔法武器
public class AdvancedStaff : ModItem
{
public override void SetDefaults()
{
Item.damage = 75;
Item.DamageType = DamageClass.Magic;
Item.mana = 15;
Item.width = 40;
Item.height = 40;
Item.useTime = 30;
Item.useAnimation = 30;
Item.useStyle = ItemUseStyleID.Shoot;
Item.knockBack = 5;
Item.value = Item.buyPrice(gold: 10);
Item.rare = ItemRarityID.Pink;
Item.UseSound = SoundID.Item20;
Item.autoReuse = true;
Item.shoot = ModContent.ProjectileType<MagicBolt>();
Item.shootSpeed = 16f;
}
public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source,
Vector2 position, Vector2 velocity, int type, int damage, float knockback)
{
// Shoot 3 projectiles in a spread
for (int i = 0; i < 3; i++)
{
Vector2 newVelocity = velocity.RotatedByRandom(MathHelper.ToRadians(15));
Projectile.NewProjectile(source, position, newVelocity, type, damage, knockback, player.whoAmI);
}
return false; // Don't shoot the default projectile
}
}
这创建了一把以扩散模式发射 3 个魔法弹的法杖,展示了高级弹幕机制。
2025 API 最佳实践
✅ 推荐做法
- • 使用 ModContent.ItemType<T>() 引用物品
- • 实现正确的空值检查
- • 遵循 C# 命名约定
- • 在多人联机环境中测试
- • 用注释记录你的代码
❌ 避免做法
- • 不要硬编码物品 ID
- • 不要在多人联机中直接访问 Main.player
- • 不要忽略编译器警告
- • 不要在 AI() 中使用重量级操作
- • 不要不必要地修改原版内容