How to Make and Call New Functions in Your Minecraft Mods

By Sarah Guthals, Stephen Foster, Lindsey Handley

A function is a way to group a lot of code and then name it. In Minecraft, you make a new function (or define or write a new function) when you drag a function block, change its name, and add code inside it. You call a function when you drag the specific function block into another function, like the main function.

Here are the primary characteristics of the main function:

  • Each mod has exactly one main function. Your mod starts at the main function, so you need to have at least one. If you had two or more, your mod wouldn’t know which one to start with. In fact, to avoid this type of confusion, each function must have a name that’s different from any other function in that mod.

  • You can create the main function by dragging a function block into the programming environment and naming it main.

  • The other coding blocks, like send message, are inside the main function.

  • Minecraft and the simulator first look for the main function and then begin running the code inside it, from top to bottom, line by line.

The main function is essential for writing mods, but there are reasons for having other functions, too. In the same way that chapters in a book let you group ideas and name those ideas, functions allow you to group code and name the grouping that results.

Here’s an example of a long main function. In this mod, two stories are being told: The Three Pigs and Goldilocks and The Three Bears.

image0.jpg

On Line 13 of the code, you can see that the modder misspelled accidentally as axidentaly. Someone might catch this mistake while testing the mod, but finding it will be difficult because you have to read each word.

image1.jpg

Finding the problem is much easier if the code uses other functions because then you can look for the error only in the Goldilocks and The Three Bears function.

image2.jpg

Having shorter functions is useful because then you can rearrange large parts of the code quickly. This image shows how simply swapping two lines of code can change the order in which the stories are told.

image3.jpg