Difference between revisions of "Modding Tutorials/Plague Gun (1.1)"

From RimWorld Wiki
Jump to navigation Jump to search
(Unbreak numbered lists)
Line 178: Line 178:
 
</source>
 
</source>
  
== C# Assembly Setup ==
+
== C# Workspace Setup ==
 
{{Main|Modding Tutorials/Setting up a solution}}
 
{{Main|Modding Tutorials/Setting up a solution}}
  
Line 213: Line 213:
  
 
'''Note:''' Exact folder names might differ between installs. The naming scheme differs slightly between the DRM-free and Steam version of the mod.
 
'''Note:''' Exact folder names might differ between installs. The naming scheme differs slightly between the DRM-free and Steam version of the mod.
 +
 +
== C# Coding ==
 +
 +
Now let's start writing the code we'll need to add custom behavior to our projectiles.
 +
 +
=== Getting Started ===
 +
# Open Class1.cs in the sidebar, usually on the write in Visual Studio.
 +
# Right-click and rename the .cs file to your liking.
 +
# Add these lines to the top this file (and every .cs file you make from now on for modding RimWorld).<source lang ="csharp">
 +
using RimWorld;
 +
using Verse;
 +
</source>
 +
#* These tell the code you're working with RimWorld. Without these, our code will not be able to understand references to RimWorld code.
 +
# Add a namespace line. By default, this is your project name. Take note - you will need this to connect to XML later.<source lang="csharp">
 +
namespace TST_PlagueGun;
 +
</source>
 +
#* '''Note:''' ''Using a prefix on the namespace is not required, but it's good for consistency and in the rare case they may overlap - such as when multiple people follow the same tutorial to learn how to mod.''
 +
 +
=== Connecting XML and C#, Part 1 ===
 +
# First, let's add a way to read XML data into your assembly.
 +
#* '''Note:''' Previous versions of this tutorial used a custom class inheriting ThingDef, which was the standard at the time, but this one will use a ModExtension, which is much less prone to various mod conflicts.
 +
# Rename public class Class1 to ModExtension_Plaguebullet and make it inherit DefModExtension. As a reminder, inheritance looks like this:<source lang="csharp">
 +
public class ModExtension_PlagueBullet : DefModExtension
 +
</source>
 +
#* '''Note:''' Renaming things in an IDE like Visual Studio is best done by pressing F2 or right-clicking the item/name. Doing it like that will change all occurrences of that thing, so everything that references your namespace or Class1 will now use the new name.
 +
# Add the following fields in ModExtension_PlagueBullet:<source lang="csharp">
 +
public float addHediffChance = 0.05f;
 +
 +
=== Writing the Projectile ===
 +
# Let's make the actual projectile. For this tutorial, we're going to make a new projectile that checks for impact and adds a Hediff (health differential - poison, toxins, implants, anything).
 +
# Make your new class inherit the Bullet class (a child of the Projectile class), so the game will treat your new projectile like a bullet and not throw (fun) errors.
 +
#

Revision as of 07:15, 21 May 2020

This tutorial is a rewrite of the original by Jecrell (Thread), updated to 1.1 by dninemfive.

Introduction

In this tutorial we will be using most of the tools available to a Rimworld modder to create a custom weapon, known as the Plague Gun.

This weapon will, when its shots hit a living target, have a chance to apply the Plague hediff ("health difference") to that target.

To do this, we will create XML `ThingDefs` for the gun and projectile, create a C# assembly which determines what happens when the projectile hits a target, and link that behavior back to the XML.

This tutorial will assume a basic familiarity with XML and C# syntax. It should be simple enough to follow if you're only a beginner.

If you have no XML or C# experience, there are good tutorials for XML here and C# here.

The Completed Mod

TODO: fork and update the repo, link here.

Required Items

Make sure to have the following installed, at least one per row:

Notepad++ or Atom orTemplate:BrSublimetext or VSCode Use any text editor that allows you to edit XML files and use "Find in Files" for referencing.
Visual Studio Community Use this or any other C# compiler to turn scripts into .dll files that RimWorld can use.
dnSpy or ILSpy This is for referencing the game's decompiled C# scripts.

For more detailed recommendations, see here.

XML Stage

In this stage we will set up the mod and create XML files which add our things to the database.

  1. Create a mod folder.Template:BrRimWorld>Mods>PlagueGun
    • Go to your RimWorld's base folder. For myself, that is D:\SteamLibrary\steamapps\common\RimWorld\. Others may find it in C:\Program Files (x86)\Steam\steamapps\common\RimWorld or a custom directory.
    • Go into the Mods folder.
    • Make a new folder with our mod's title: PlagueGun
  2. Inside PlagueGun, make an About folder.Template:BrRimWorld>Mods>PlagueGun>About
  3. Inside the About folder, make a new text file and rename it About.xml.Template:BrRimWorld>Mods>PlagueGun>About>About.xml
    • You will need a good text editor to make a proper XML file -- see required items. I always make a .txt file first and change it to .xml. If you can't rename your file's type, make sure you have filetypes visible in your operating system's file view settings.
    • About.xml is the file that shows your mod in the mod list inside the RimWorld game. It is also used when creating a Workshop upload for Steam.
    • At the top of an XML file, always include this for RimWorld. It basically just gives the game some info about how to read the file.
      <?xml version="1.0" encoding="utf-8"?>
      Note: the version tag should always be "1.0". It has no relation with the current RimWorld version.
    • Then add the MetaData tags for the Workshop and in-game Mod list.
      <ModMetaData>
        <name>Test Mod - Plague Gun</name> <!-- The name of your mod in the mod list -->
        <author>YourNameHere</author>
        <packageId>YourNameHere.PlagueGun</packageId> <!-- a unique identifier for your mod. Must contain only a-z and periods, no spaces. -->
        <supportedVersions> <!-- the version(s) your mod supports -->
          <li>1.1</li>
        </supportedVersions>
        <description>This mod adds a plague gun, a weapon that has a chance to give your enemies the plague.\n\nFor version 1.1.</description>
      </ModMetaData>
    • Save the file.
  4. Add a Preview.png or Preview.jpeg to your About folder.Template:BrRimWorld>Mods>PlagueGun>About>Preview.png
    • This lets users see what your mod looks like in the RimWorld mod list or on the Steam Workshop.
    • The conventional dimensions to fit the preview image on Steam are 640x360. The image must be smaller than 1mb.
    • Example: Preview.png
  5. Make a Defs folder in your Mod's directory.Template:BrRimWorld>Mods>PlagueGun>Defs
    • RimWorld will read your XML files in any subdirectory of Defs. You can name your directories however you like under that folder. Defs>StrangeNewAlienGuns>MyGuns.xml will work. For the purposes of this tutorial, however, we will use the RimWorld standard structure.
    • What are Defs? Main article: Defs
      • RimWorld uses things called Defs (short for "definitions") like blueprints for in-game objects. Instead of using hidden C# code, RimWorld will look up an XML Def and copy it to the game world. This makes things easier for us, the modders. Everything from characters, animals, floors, damages, buildings, and even diseases in RimWorld use Defs. We're going to make Defs for our Plague Gun and Plague Bullet.
  6. Make a new ThingDefs folder in your Defs folder.Template:BrRimWorld>Mods>PlagueGun>Defs>ThingDefs
  7. Make a new text file in your ThingDefs folder, and change it to RangedWeapon_PlagueGun.xml.Template:BrRimWorld>Mods>PlagueGun>Defs>ThingDefs>RangedWeapon_PlagueGun.xml
    • This file will contain the blueprints (ThingDefs) for our new gun and bullets.
    • Next we will fill out our XML file by copying an existing revolver's ThingDef and a revolver bullet ThingDef.
    • In RimWorld, it is often best to use the XML attribute ParentName="BaseBullet" when making a bullet, because it will copy XML code from a pre-existing BaseBullet ThingDef, which can save us time and key taps. Main article: Inheritance
  8. First, add our favourite line to the top.
    <?xml version="1.0" encoding="utf-8"?>
  9. Add the <Defs> opening and closing tags to the XML to hold our new code.
    <?xml version="1.0" encoding="utf-8"?>
    <Defs>
    
    </Defs>
  10. Use your text editor. Use its "Find in Files" function to reference and copy Bullet_Revolver to your XML file.
    • For me, Find in Files is a function I use repeatedly. In Notepad++, if you press CTRL+SHIFT+F, you can go to the Find in Files screen. From there, you can enter a phrase to search for, and then you can enter the file path to search through. This makes it wildly easier to search for examples in RimWorld's Core. RimWorld holds copies of all of its weapons, items, buildings, etc. inside the Mods/Core directory.
    • So, start by using Find in Files... and find this: defName>Bullet_Revolver
    • When you find Bullet_Revolver, copy from its beginning <ThingDef> all the way until its closing </ThingDef> tag into your XML File.
  11. Use your text editor's "Find in Files" function to reference and copy Gun_Revolver to your XML file.
    • Typically, Gun_Revolver is right below Bullet_Revolver in XML, so hopefully this will be easy to find and copy.
    • Again, copy the ThingDef block to your new XML file.
  12. Change the defName, labels, and other stats of Bullet_Revolver and Revolver in your XML file to make them unique.
    • Change the <defaultProjectile> tag inside the PlagueGun's Verbs to use the defName of your bullet (TST_Bullet_PlagueGun). Failing to do this will result in a no errors, but your gun will shoot regular bullets (and not give the plague effect). Template:BrOnce again, under the verbs. Please make sure <defaultProjectile> references the bullet. e.g.
      <defaultProjectile>TST_Bullet_PlagueGun</defaultProjectile>
    • TIP: Use prefixes to avoid conflicting with other mods. RimWorld will overwrite any def with <defName>Tobacco</defName>, for instance, if it finds another with the same defName. If two modders use different prefixes, however, e.g. <defName>VGP_Tobacco</defName> and <defName>ROM_Tobacco</defName>, no conflict will occur, and both mods can co-exist. This tutorial uses TST_ for its example prefix. Main article: Compatibility
    • By contrast, labels, descriptions, and other non-defName tags can generally be non-unique without a risk of conflicts, except perhaps confusion for the end user.

If all you were interested in is making a gun mod, you are done. You'll of course want to edit values like the damage it does, and test your mod. You'll also want to change the texturePath to your unique art, and whatever else.

Completed Example

Note: The example is up-to-date for 1.1 and will likely be outdated in the future. The above steps should always be relevant.

<?xml version="1.0" encoding="utf-8" ?>
<Defs>
  <ThingDef ParentName="BaseBullet">
    <defName>TST_Bullet_PlagueGun</defName>
    <label>plague bullet</label>
    <graphicData>
      <texPath>Things/Projectile/Bullet_Small</texPath>
      <graphicClass>Graphic_Single</graphicClass>
    </graphicData>
    <projectile>
      <flyOverhead>false</flyOverhead>
      <damageDef>Bullet</damageDef>
      <damageAmountBase>12</damageAmountBase>
      <stoppingPower>1</stoppingPower>
      <speed>55</speed>
    </projectile>
  </ThingDef>

  <ThingDef ParentName="BaseHumanMakeableGun">
    <defName>TST_Gun_PlagueGun</defName>
    <label>plague gun</label>
    <description>A curious weapon notable for its horrible health effects.</description>
    <graphicData>
      <texPath>Things/Item/Equipment/WeaponRanged/Revolver</texPath>
      <graphicClass>Graphic_Single</graphicClass>
    </graphicData>
    <soundInteract>Interact_Revolver</soundInteract>
    <statBases>
      <WorkToMake>4000</WorkToMake>
      <Mass>1.4</Mass>
      <AccuracyTouch>0.80</AccuracyTouch>
      <AccuracyShort>0.75</AccuracyShort>
      <AccuracyMedium>0.45</AccuracyMedium>
      <AccuracyLong>0.35</AccuracyLong>
      <RangedWeapon_Cooldown>1.6</RangedWeapon_Cooldown>
    </statBases>
    <weaponTags>
      <li>SimpleGun</li>
      <li>Revolver</li>
    </weaponTags>
    <costList>
      <Steel>30</Steel>
      <ComponentIndustrial>2</ComponentIndustrial>
    </costList>
    <recipeMaker>
      <skillRequirements>
        <Crafting>3</Crafting>
      </skillRequirements>
    </recipeMaker>
    <verbs>
      <li>
        <verbClass>Verb_Shoot</verbClass>
        <hasStandardCommand>true</hasStandardCommand>
        <defaultProjectile>TST_Bullet_PlagueGun</defaultProjectile>
        <warmupTime>0.3</warmupTime>
        <range>25.9</range>
        <soundCast>Shot_Revolver</soundCast>
        <soundCastTail>GunTail_Light</soundCastTail>
        <muzzleFlashScale>9</muzzleFlashScale>
      </li>
    </verbs>
    <tools>
      <li>
        <label>grip</label>
        <capacities>
          <li>Blunt</li>
        </capacities>
        <power>9</power>
        <cooldownTime>2</cooldownTime>
      </li>
      <li>
        <label>barrel</label>
        <capacities>
          <li>Blunt</li>
          <li>Poke</li>
        </capacities>
        <power>9</power>
        <cooldownTime>2</cooldownTime>
      </li>
    </tools>
  </ThingDef>
</Defs>

C# Workspace Setup

Next, we will set up a workspace to write C# code, which is a little bit more involved than just using a text editor.

  1. Open your compiler of choice for C#.
    • This tutorial will assume you're using Visual Studio Community edition, a free Windows-based compiler for C# code.
  2. Make a new Visual C# Class Library .NET Framework project. Name it PlagueGun. Make its directory RimWorld>Mods>PlagueGun>Source
    • File → New → Project → Class Library (.NET Framework).
    • Don't get this confused with "Class Library (.NET Standard)" or "Class Library (.NET Core)"!
  3. Go into the project properties.
    • Project → PlagueGun Properties.
  4. In that window, change the Target Framework version to .NET Framework 4.7.2
    • Forgetting to do this will cause lots of errors.
    • Select Yes when it asks you if you're sure to change the framework.
  5. Go to the Build tab.
  6. Change the output path to be RimWorld\Mods\PlagueGun\Assemblies
    • All .dll files will go into this directory when we "build" our code library.
  7. In that same window, click the Advanced... button.
  8. Change Debugging Information to none.
    • This prevents a simple error that occurs when RimWorld doesn't know what to do with the debug .pdb files.
  9. In Solution Explorer. Go into Properties and edit AssemblyInfo.cs. Change the name of your assembly and assembly file version number as you like.
    • This doesn't have to all be the same as your namespace, but it doesn't hurt to be consistent.
  10. In the main option bar at the top of the visual studio (File, Edit, View...), click Project, and click Add Reference.
  11. Click Browse and go to RimWorld\RimWorldWin64_Data\Managed
  12. Add references to Assembly-CSharp.dll and UnityEngine.CoreModule.dll
    • In 1.1 the Unity DLLs were split up and are no longer all contained in the same module. For our purposes we only need the core module.
  13. In the Solution Explorer (typically on the right side of the application), look at the references drop down list.
  14. Select Assembly-CSharp. Check the Properties section (usually under Solution Explorer). Make sure the properties section has Copy Local set to FALSE.
  15. Do this (Copy Local to FALSE) for UnityEngine.CoreModule as well.
    • By doing this, we prevent the project from causing one million hash conflicts by copying the entire game's code twice!

Now the workspace setup is complete and we can add C# code to RimWorld.

Note: Exact folder names might differ between installs. The naming scheme differs slightly between the DRM-free and Steam version of the mod.

C# Coding

Now let's start writing the code we'll need to add custom behavior to our projectiles.

Getting Started

  1. Open Class1.cs in the sidebar, usually on the write in Visual Studio.
  2. Right-click and rename the .cs file to your liking.
  3. Add these lines to the top this file (and every .cs file you make from now on for modding RimWorld).
    using RimWorld;
    using Verse;
    • These tell the code you're working with RimWorld. Without these, our code will not be able to understand references to RimWorld code.
  4. Add a namespace line. By default, this is your project name. Take note - you will need this to connect to XML later.
    namespace TST_PlagueGun;
    • Note: Using a prefix on the namespace is not required, but it's good for consistency and in the rare case they may overlap - such as when multiple people follow the same tutorial to learn how to mod.

Connecting XML and C#, Part 1

  1. First, let's add a way to read XML data into your assembly.
    • Note: Previous versions of this tutorial used a custom class inheriting ThingDef, which was the standard at the time, but this one will use a ModExtension, which is much less prone to various mod conflicts.
  2. Rename public class Class1 to ModExtension_Plaguebullet and make it inherit DefModExtension. As a reminder, inheritance looks like this:
    public class ModExtension_PlagueBullet : DefModExtension
    • Note: Renaming things in an IDE like Visual Studio is best done by pressing F2 or right-clicking the item/name. Doing it like that will change all occurrences of that thing, so everything that references your namespace or Class1 will now use the new name.
  3. Add the following fields in ModExtension_PlagueBullet:<source lang="csharp">

public float addHediffChance = 0.05f;

Writing the Projectile

  1. Let's make the actual projectile. For this tutorial, we're going to make a new projectile that checks for impact and adds a Hediff (health differential - poison, toxins, implants, anything).
  2. Make your new class inherit the Bullet class (a child of the Projectile class), so the game will treat your new projectile like a bullet and not throw (fun) errors.