Modding:Adding Code to the Player: Difference between revisions

Add CallAfterGameLoadedAttribute
m (Updated example)
(Add CallAfterGameLoadedAttribute)
Line 4: Line 4:
|type=This article presupposes some knowledge of [[Modding/C Sharp Scripting|C# scripting]].
|type=This article presupposes some knowledge of [[Modding/C Sharp Scripting|C# scripting]].
|format=tiny}}
|format=tiny}}
== Add Code to Player on a New Game ==


You can use the <code>[PlayerMutator]</code> attribute and <code>IPlayerMutator</code> interface to modify the player object before the game begins, immediately after the player <code>GameObject</code> is first created.
You can use the <code>[PlayerMutator]</code> attribute and <code>IPlayerMutator</code> interface to modify the player object before the game begins, immediately after the player <code>GameObject</code> is first created.
Line 27: Line 29:
       }
       }
   }
   }
</syntaxhighlight>
== Add Code to Player on a Save Load ==
You can use the <code>[HasCallAfterGameLoadedAttribute]</code> and <code>[CallAfterGameLoadedAttribute]</code> 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.
<syntaxhighlight lang="csharp">
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.
        }
    }
}
</syntaxhighlight>
</syntaxhighlight>