While most modding is about changing game play, sometimes you want to give the player more power -- give them commands that allow them to "cheat".
In this tutorial I explain how create a custom command.
I use the example of a "conjure" command that acts like summon but for my custom entities.
The built in /summon command can call custom entities by pre-pending the mod id before the name of the entity, such as /summon wildanimals.Elephant.
However, for convenience and fun I don't like putting the modid in front so created my own equivalent command called "conjure" that spawns your named entity at the player's location. So this way I can just use /conjure Elephant.
In any case, it is useful to know how to create your own server command so here is an example for based on this conjure idea.
Create Custom Command Class Implementing ICommand
I based this portion off of the tutorial at: Forge Wiki Command Tutorial
Follow these steps:
- Create a class that implements ICommand.
- Eclipse should warn you about unimplemented methods; accept the suggestion to implement the unimplemented methods.
- Then put your custom code inside those methods. For example:
There are a few things to note. The actual command name is specified by the getCommandName() method, but you can also add aliases (other words that will also act to invoke the command). These aliases should be added in the command class constructor.
Tip: People often use aliases to allow for abbreviated command names.
The canCommandSenderUseCommand() method can be used to filter out which users are allowed to use the command. In my case I wanted all users to be allowed so I returned true.
The getCommandUsage() is important as it defines the format of the command. For example, in this case in addition to the command itself I wanted to pass an additional text argument (in my case the name of the entity).
The "real work" of the command happens in the processCommand() method. Here you can do anything you want. In my case I am using the additional text argument of the command and using it to look up registered entities. If I find that there is an entity registered with that name I will spawn it at the player location, otherwise I post an error message to the chat.
Tip: It is usually a good idea to send chat messages to indicate the success or failure of the command.
Register Command In serverLoad() Event In Your Main Mod Class
Similar to how the preInit() and init() methods are put into the main class (or common proxy) of your mod, there is another "FML life cycle event" called the FMLServerStartingEvent that makes a good place to register the server commands. You just need to annotate the handling method with the @EventHandler annotation.
I hope this helps you have fun creating custom commands. Please feel free to contact me with any suggestions for corrections or clarifications!