Modding:Code Tutorial Simple Item: Difference between revisions

From Vintage Story Wiki
(Created page.)
 
mNo edit summary
Line 7: Line 7:


=== Objective ===
=== Objective ===
In this tutorial, you will be introduced to code modding by creating a block with custom functionality. You will create the assets for this project, find out how block classes are registered, and use a number of different functions. The block you will be creating is a trampoline, where as an entity collides with it, they will bounce.
In this tutorial, you will be creating an item with basic custom functionality. You will find out how item classes are registered, and how to interact further with entities. The item you will be creating is a new 'thorny' sword, which will slightly hurt the player when used to attack.
 
Please note that this tutorial is quite detailed since it is the first in the code tutorial series. If you are new to modding, it is highly recommended to follow each of these steps.  


=== Prerequisites ===
=== Prerequisites ===
Line 20: Line 18:


* [[Modding:Code Tutorial Essentials|Code Tutorial Essentials]]
* [[Modding:Code Tutorial Essentials|Code Tutorial Essentials]]
It is also highly recommended to have completed previous tutorial in the code series:
* [[Modding:Code Tutorial Simple Block|Simple Block Class]]


== Assets ==
== Assets ==
[[File:VisualStudioOpenAssetsFolderInExplorerNeat.png|right|frameless]]
This tutorial uses the finished project from the previous tutorial. If you need to, you can download the finished version of the previous tutorial from GitHub [https://github.com/Nateonus/vsmodexamples/raw/master/updated_code_mod_tutorials/zipped-tutorials/VSTutorial%20-%201%20-%20Simple%20Block%20Tutorial.zip here].  
Before you get started with any coding, it is important that you create the assets for your new trampoline block.
 
In Visual Studio, your mod's assets are easy to access from the ''solution explorer.'' Right click on the folder called ''assets'', and then select ''Open Folder in File Explorer''. This will open the assets folder for your mod, which is an identical format to the assets folder in content mods. The opened folder should only contain another folder labeled ''vstutorial''.


You need to add a few asset files for the trampoline. As always, these can be downloaded from GitHub [https://github.com/Nateonus/vsmodexamples/releases/tag/CodeSimpleBlock here].
As usual, you need the required assets for this tutorial. These can be downloaded from GitHub [https://github.com/Nateonus/vsmodexamples/releases/tag/CodeSimpleItem here], and should replace the entirety of your assets folder as it also contains the previous tutorial's assets. When these files are added, you should have new itemtype, shape, and texture files.  


The downloaded zip file contains a folder called ''vstutorial.'' Copy this folder over your own, and the asset files will be added. You can verify this by going back to Visual Studio, looking at the solution explorer, and expanding the assets folder. You should now have a trampoline block type, as well as a lang and texture file.
Run the game, launch a world, and check the creative menu. You should be able to find the "Thorns Blade".
 
Run the game, launch a world, and check the creative menu. You should see the trampoline block. It looks fancy, but has absolutely no functionality yet.
{| class="wikitable mw-collapsible mw-collapsed"
{| class="wikitable mw-collapsible mw-collapsed"
|Playing Vintage Story in fullscreen mode?
|Playing Vintage Story in fullscreen mode?
Line 38: Line 34:
|}
|}


== Block Class ==
== Item Class ==
Close the game and go back to Visual Studio. To add custom functionality to the trampoline block, you'll need to create a '''block class'''.
Close the game and go back to Visual Studio. To add custom functionality to the item, you'll need to create an '''item class'''.  
 
A block class is a script that offers custom functionality for any specific blocktype assets. Note that each blocktype can only have a single attached block class.
 
=== Creating a Block Class ===
Before you create a new block class, you should create a new folder called 'Blocks'. It is good practice to keep your classes and other scripts in folders relevant to what they are. In the solution explorer, right click on ''VSTutorial'' (the project, not the one labelled ''solution''), hover over ''Add'', and click ''New Folder''. You can then enter a name for your folder.
 
You need a name for your new block's class. Generally, classes in Vintage Story follow the naming convention of {Type}{Name}. So, in the example of a trampoline block class, you should call this block class "BlockTrampoline".
 
With your folder now created, you need to create a new class. Right click the new folder, hover over ''Add'', and select ''Class''. This will open a menu with a lot of templates, and an input field to enter your class name. Make sure you have selected the standard ''Class'' at the top of the template list, and enter the name 'BlockTrampoline.cs'. Click ''Add'', and your class will be created.


The trampoline block's class should open automatically, but you can open it manually by double clicking its entry in the solution explorer.
An item class is a script that offers custom functionality for any specific itemtype assets. Note that each itemtype can only have a single attached item class.  


=== Explaining Block Classes ===
Creating an item class is extremely similar to creating a block class.
Let's have a quick run down of how a block class works. Replace the entire contents of the new class with the following code:
{| class="wikitable mw-collapsible mw-collapsed"
|BlockTrampoline.cs
|-
|<syntaxhighlight lang="csharp" line="1">
//Here are the imports for this script. Most of these will add automatically.
using Vintagestory.API.Common;
using Vintagestory.API.MathTools;


/*
=== Creating an Item Class ===
* The namespace the class will be in. This is essentially the folder the script is found in.
To keep the code organized, you should create a new folder called "Items". Right click on your project, hover over add, and select ''New Folder''.  
* If you need to use the BlockTrampoline class in any other script, you will have to add 'using VSTutorial.Blocks' to that script.
*/
namespace VSTutorial.Blocks
{
    /*
    * The class definition. Here, you define BlockTrampoline as a child of Block, which
    * means you can 'override' many of the functions within the general Block class.
    */
    internal class BlockTrampoline : Block
    {
        //Any code within this 'override' function will be called when a trampoline block is placed.  
        public override void OnBlockPlaced(IWorldAccessor world, BlockPos blockPos, ItemStack byItemStack = null)
        {
            //Log a message to the console.
            api.Logger.Event("Trampoline Block Placed!");
            //Perform any default logic when our block is placed.
            base.OnBlockPlaced(world, blockPos, byItemStack);
        }


        //Any code within this 'override' function will be called when a trampoline block is broken.
You need a name for the new item class. These follow the same convention as the Blocks, and most other types. In this case, our thorny blade item class, you should name this class "ItemThornsBlade".  
        public override void OnBlockBroken(IWorldAccessor world, BlockPos pos, IPlayer byPlayer, float dropQuantityMultiplier = 1)
        {
            //Log a message to the console.
            api.Logger.Event("Trampoline Block Broken!");
            //Perform any default logic when our block is broken (e.g., dropping the block as an item.)
            base.OnBlockBroken(world, pos, byPlayer, dropQuantityMultiplier);
        }
    }
}
</syntaxhighlight>
|}
Note the code comments throughout the file. These are marked by double slashes ( // '')'' or any text between /* and */. These give brief explanations on what every line of this example does.


For further explanation, on line 15, the ''BlockTrampoline'' class is defined as a child of the ''Block'' class, which is in turn a child of the ''CollectibleObject'' class, and then the ''RegistryObject class''. This essentially means that any function within these three inherited classes marked as '<nowiki/>''virtual''<nowiki/>', '<nowiki/>''abstract'<nowiki/>'', or '<nowiki/>''override''' can be given custom functionality. For an exhaustive list of functions and attributes that can be overriden, take a look at the API documentation for the [https://apidocs.vintagestory.at/api/Vintagestory.API.Common.Block.html#methods Block] and [https://apidocs.vintagestory.at/api/Vintagestory.API.Common.CollectibleObject.html#methods CollectibleObject] methods.
Create your new class. Right click the new folder, hover over ''Add'', and select ''Class''. Ensure you have the standard ''Class'' selected in the template list, enter your class name, and click create.
{| class="wikitable mw-collapsible mw-collapsed"
|Why so many code comments?
|-
|There is much debate about how many code comments are too many, and when/where they should be used. Although many people who are experienced with C# or other C programming languages may find this code easy to understand, this tutorial is designed for those who may not have ever used a C programming language, or even any programming language.  
|}


=== Registering the Block Class ===
=== Registering the Block Class ===