Skip to content

Cross Mod Things

Rijam edited this page Aug 2, 2024 · 2 revisions

What if we want our Town NPC to interact with things from other mods, such as selling items, happiness, and chat? We can do all of those things without adding the other mods as a strong or weak reference.

Chat

In GetChat(), we can do something like this:

// First check if the mod is enabled
if (ModLoader.TryGetMod("ExampleMod", out Mod exampleMod)) {
	// Next, try to find the other Town NPC.
	// Using TryFind<>() is safer than using Find<>()
	// If the NPC we are trying to find doesn't exist, our mod will continue to work.
	if (exampleMod.TryFind<ModNPC>("ExamplePerson", out ModNPC examplePersonModNPC)) {
		int examplePerson = NPC.FindFirstNPC(examplePersonModNPC.Type);
		if (examplePerson >= 0) {
			chat.Add(Language.GetTextValue("Mods.TownNPCGuide.NPCs.TutorialTownNPC.Dialogue.ExamplePerson", Main.npc[examplePerson].FullName), 2);
		}
	}
}

When finding the other Town NPC, we need to search for the NPC's class name.

Shop

In AddShops(), we can do something like this:

// First check if the mod is enabled
if (ModLoader.TryGetMod("ExampleMod", out Mod exampleMod)) {
	// Next, try to find the item.
	// Using TryFind<>() is safer than using Find<>()
	// If the item we are trying to find doesn't exist, our mod will continue to work.
	if (exampleMod.TryFind<ModItem>("ExampleJoustingLance", out ModItem exampleJoustingLance)) {
		npcShop2.Add(exampleJoustingLance.Type);
	}
}

// Actually, we don't even need to check to see if the mod is enabled.
// We can specify the mod name when we try to find the item. This is still safe because the item won't get added if TryFind fails.
if (ModContent.TryFind<ModItem>("ExampleMod/ExamplePaperAirplane", out ModItem examplePaperAirplane)) {
	npcShop2.Add(examplePaperAirplane.Type);
}

When finding the other item, we need to search for the item's class name.

Make sure the item exists before you try adding the item to the shop. If you try to add null as the item, your mod will fail to load with other mod enabled.

Happiness

In our GobalNPC class in SetStaticDefaults(), we can do something like this:

// First check if the mod is enabled
if (ModLoader.TryGetMod("ExampleMod", out Mod exampleMod)) {
	// Next, try to find the other Town NPC.
	// Using TryFind<>() is safer than using Find<>()
	// If the NPC we are trying to find doesn't exist, our mod will continue to work.
	if (exampleMod.TryFind<ModNPC>("ExamplePerson", out ModNPC examplePersonModNPC)) {
		// Get their happiness
		var examplePersonHappiness = NPCHappiness.Get(examplePersonModNPC.Type);
		var tutorialTownNPCHappiness = NPCHappiness.Get(tutorialTownNPC);

		// Make them love each other!
		examplePersonHappiness.SetNPCAffection(tutorialTownNPC, AffectionLevel.Love);
		tutorialTownNPCHappiness.SetNPCAffection(examplePersonModNPC.Type, AffectionLevel.Love);
	}
}


Clone this wiki locally