Modding:Adding Code to the Player

From Caves of Qud Wiki
Jump to navigation Jump to search
This page is about modding. See the modding overview for an abstract on modding.
This page is about modding. See the modding overview for an abstract on modding.
For best results, it's recommended to have read the following topics before this one:

Add Code to Player on a New Game

You can use the [PlayerMutator] attribute and IPlayerMutator interface to modify the player object before the game begins, immediately after the player GameObject is first created.

This method works only when the player starts a New Game. If a player loads your mod on an existing save, [PlayerMutator] code is never called.

This structure allows you to run custom code on the player object. For example, you might add custom parts to the player from your mod, which is otherwise very difficult to do.

Any class tagged with the PlayerMutator attribute is instantiated after the player object is created and assigned, and the mutate method is called with the player as the parameter. For example:

  using XRL; // to abbreviate XRL.PlayerMutator and XRL.IPlayerMutator
  using XRL.World; // to abbreviate XRL.World.GameObject
  
  [PlayerMutator]
  public class MyPlayerMutator : IPlayerMutator
  {
      public void mutate(GameObject player)
      {
          // modify the player object when a New Game begins
          // for example, add a custom part to the player:
          player.AddPart<MyCustomPart>();
      }
  }

Add Code to Player on a Save Load

You can use the [HasCallAfterGameLoadedAttribute] and [CallAfterGameLoadedAttribute] attributes to modify the player object whenever a save game is loaded. This method can be useful if you want your mod changes to apply even to existing save games (rather than just new games).

Note that this method works only on loaded saves - if you want your code to also run on a new game, you must combine this method with the PlayerMutator method described above.

using XRL; // for HasCallAfterGameLoadedAttribute and CallAfterGameLoadedAttribute
using XRL.Core; // for XRLCore
using XRL.World; // for GameObject
  
[HasCallAfterGameLoadedAttribute]
public class MyLoadGameHandler
{
    [CallAfterGameLoadedAttribute]
    public static void MyLoadGameCallback()
    {
        // Called whenever loading a save game
        GameObject player = XRLCore.Core?.Game?.Player?.Body;
        if (player != null)
        {
            player.RequirePart<MyCustomPart>(); //RequirePart will add the part only if the player doesn't already have it. This ensures your part only gets added once, even after multiple save loads.
        }
    }
}