### Example Setup Method with HStats Initialization Source: https://hytalemodding.dev/en/docs/guides/plugin/tracking-mod-analytics-with-hstats This is an example of how your mod's setup method should look after initializing HStats. It includes the necessary line to start tracking. ```java @Override protected void setup() { super.setup(); new HStats("c34a2b2a-afd8-4d6a-821e-7a63e12c5ea6", "1.0.0"); } ``` -------------------------------- ### Example Plugin Setup Source: https://hytalemodding.dev/en/docs/guides/ecs/example-ecs-plugin This is the main plugin class that sets up the game. It registers the custom command, event listeners, component, and system. ```java package scot.oskar.hytaletemplate; import dev.hytale.plugin.JavaPlugin; import dev.hytale.plugin.JavaPluginInit; import dev.hytale.ecs.component.ComponentType; import dev.hytale.ecs.entity.EntityStore; import scot.oskar.hytaletemplate.commands.ExampleCommand; import scot.oskar.hytaletemplate.components.PoisonComponent; import scot.oskar.hytaletemplate.events.ExampleEvent; import scot.oskar.hytaletemplate.systems.PoisonSystem; import scot.oskar.hytaletemplate.systems.ChatFormatter; import dev.hytale.event.PlayerChatEvent; import dev.hytale.event.PlayerReadyEvent; import javax.annotation.Nonnull; public final class ExamplePlugin extends JavaPlugin { private static ExamplePlugin instance; public ExamplePlugin(@Nonnull JavaPluginInit init) { super(init); instance = this; } @Override protected void setup() { this.getCommandRegistry().registerCommand(new ExampleCommand()); this.getEventRegistry().registerGlobal(PlayerReadyEvent.class, ExampleEvent::onPlayerReady); this.getEventRegistry().registerGlobal(PlayerChatEvent.class, ChatFormatter::onPlayerChat); // Register the component & set the type in the component class so its easier to retrieve. ComponentType poisonComponentType = this.getEntityStoreRegistry() .registerComponent(PoisonComponent.class, PoisonComponent::new); PoisonComponent.setComponentType(poisonComponentType); this.getEntityStoreRegistry().registerSystem(new PoisonSystem(PoisonComponent.getComponentType())); } public static ExamplePlugin get() { return instance; } } ``` -------------------------------- ### Guide Frontmatter Example Source: https://hytalemodding.dev/en/docs/contributing/writing-guides Metadata for a guide file, including title, description, author information, and an icon. Ensure indentation is consistent. ```markdown --- title: "Java Basics" description: "Learn the basics of Java programming." authors: - name: "Your Name" url: "https://yourwebsite.com" icon: YourIcon --- ``` -------------------------------- ### Instance Configuration Example Source: https://hytalemodding.dev/en/docs/official-documentation/worldgen/worldgen-tutorial/README An example of an Instance.bson configuration file, specifying world generation settings. ```json { "WorldGen": { "Type": "HytaleGenerator", "WorldStructure": "Basic", "playerSpawn": { "X": 123, "Y": 480, "Z": 10000, "Pitch": 0, "Yaw": 0, "Roll": 0 } } } ``` -------------------------------- ### Setting the Start State for an NPC Role Source: https://hytalemodding.dev/en/docs/guides/npc-workings/npc-states This example demonstrates how to set the initial state for an NPC's role. It ensures that the NPC begins in the 'Idle' state, preventing validation errors. ```json { "StartState":"Idle", "Instructions":[ { "Instructions":[ { "Sensor":{ "Type":"State", "State":"Idle" }, "Actions":[ { "Type":"Nothing" } ] } ] } ] } ``` -------------------------------- ### Verify Tool Installation Source: https://hytalemodding.dev/en/docs/guides/plugin/browsing-serverjar Verify that Git, Maven, and Java are installed and accessible in your system's PATH. ```bash git --version ``` ```bash mvn --version ``` ```bash java --version ``` ```bash jar --version ``` -------------------------------- ### Install Dependencies Source: https://hytalemodding.dev/en/docs/guides/plugin/browsing-serverjar Install the project dependencies using pip within the activated virtual environment. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install OpenJDK 25 via Scoop on Windows Source: https://hytalemodding.dev/en/docs/guides/plugin/setting-up-env Use Scoop, a command-line installer for Windows, to install OpenJDK 25. This is an alternative to the installer method. ```bash scoop bucket add java scoop install java/openjdk25 ``` -------------------------------- ### Initialize HStats in Main Class Source: https://hytalemodding.dev/en/docs/guides/plugin/tracking-mod-analytics-with-hstats Add this line to your mod's setup method to start tracking analytics with HStats. Replace 'YOUR-MOD-UUID' with your mod's unique identifier and '1.0.0' with your mod's version. ```java new HStats("YOUR-MOD-UUID", "1.0.0"); ``` -------------------------------- ### Get Command Help Source: https://hytalemodding.dev/en/docs/guides/prefabs Displays help information for any prefab-related command, showing available options and usage. ```bash /prefab save --help ``` -------------------------------- ### NPC State Machine Example Source: https://hytalemodding.dev/en/docs/guides/npc-workings/npc-states A comprehensive example demonstrating NPC state transitions, including sub-states like 'Farm.Goto' and 'Farm.Jobdriver'. This illustrates how to manage complex NPC behaviors. ```json { "StartState":"Idle", "Instructions":[ { "Instructions":[ { "$Comment":"Timer initialization.", "Sensor":{ "Type":"Any", "Once":true } }, { "$Comment":"Work timer is triggered and we will check if we can do farm work. If we can go to the Farm state.", "Continue":true, "Actions":[ { "Type":"State", "State":"Farm.Goto" } ] }, { "Sensor":{ "Type":"State", "State":"Idle" } }, { "$Comment":"Main state of 'Farm' where our logic lies in.", "Sensor":{ "Type":"State", "State":"Farm.Goto" }, "Instructions":[ { "$Comment":"Perform checks to see if our Farming state fails, and if it does go back to being Idle.", "Continue":true }, { "$Comment":"Go to our designated farming area.", "Sensor":{ "Type":"State", "State":".Goto" }, "Instructions":[ { "$Comment":"Reached our destination. Switch to '.Jobdriver' sub-state.", "Actions":[ { "Type":"State", "State":".Jobdriver" } ] } ] }, { "$Comment":"Perform farming job until we no longe can.", "Sensor":{ "Type":"State", "State":".Jobdriver" } } ] } ] } ] } ``` -------------------------------- ### ServerRulesCommand Example Source: https://hytalemodding.dev/en/docs/guides/plugin/creating-commands An example of an AbstractAsyncCommand that lists server rules. This command runs on a background thread and cannot directly edit world data. ```java public class ServerRulesCommand extends AbstractAsyncCommand { public ServerRulesCommand() { super("rules", "Lists the servers rules"); } @Override protected CompletableFuture executeAsync(@Nonnull CommandContext context) { context.sendMessage(Message.raw("The only rule is there are no rules.")); return CompletableFuture.completedFuture(null); } } ``` -------------------------------- ### Walk Motion Controller Example Source: https://hytalemodding.dev/en/docs/guides/npc-workings/npc-role An example configuration for a 'Walk' motion controller, specifying parameters like MaxWalkSpeed, Gravity, and Acceleration. This is typically used for ground-based NPCs. ```json "MotionControllerList": [ { "Type": "Walk", "MaxWalkSpeed": { "Compute": "MaxSpeed" }, "Gravity": 10, "RunThreshold": 0.3, "MaxFallSpeed": 15, "MaxRotationSpeed": 360, "Acceleration": 10 } ] ``` -------------------------------- ### NPC State Configuration Example Source: https://hytalemodding.dev/en/docs/official-documentation/npc/10-attack-a-player Example of an NPC state configuration, showing sensor types and actions. ```json { "Attitudes": ["Hostile"] } }, "Actions": [ { "Type": "State", "State": "Alerted" } ] }, { "Sensor": { "Type": "State", "State:" ".Default" }, ... ``` -------------------------------- ### BlockSpawner Plugin Example Source: https://hytalemodding.dev/en/docs/established-information/server-plugin-insights A basic plugin example demonstrating how to define custom block spawning rules. It utilizes the asset system and codecs for serialization. ```java public class BlockSpawner { // ... plugin code ... } ``` -------------------------------- ### GlobalUpdateSystem Example Source: https://hytalemodding.dev/en/docs/guides/ecs/systems An example of a TickingSystem that runs once per tick globally. Use this for world-wide updates or logic not targeting specific entities. ```java public class GlobalUpdateSystem extends TickingSystem { @Override public void tick(float dt, int index, Store store) { World world = store.getExternalData().getWorld(); } } ``` -------------------------------- ### Basic Callout Source: https://hytalemodding.dev/en/docs/contributing/writing-guides Use this syntax to create a basic callout to highlight important information or tips within a guide. ```html This is a callout message. ``` -------------------------------- ### Java Substring Indexing Example Source: https://hytalemodding.dev/en/docs/guides/java-basics/09-string Clarifies how `substring(start, end)` works in Java, including the start and end indices and the exclusion of the character at the end index. ```Java String text = "Hytale"; // 012345 (indices) text.substring(0, 2); // "Hy" (indices 0 and 1) text.substring(2, 6); // "tale" (indices 2, 3, 4, 5) text.substring(2); // "tale" (from 2 to end) ``` -------------------------------- ### ExamplePlugin - Registers Components and Systems Source: https://hytalemodding.dev/en/docs/guides/ecs/block-components This plugin class is responsible for initializing and registering custom components and systems within the Hytale ECS. It ensures that the ExampleBlock component and related systems are available to the game. ```java public class ExamplePlugin extends JavaPlugin { protected static ExamplePlugin instance; private static final HytaleLogger LOGGER = HytaleLogger.forEnclosingClass(); private ComponentType exampleBlockComponentType; public static ExamplePlugin get() { return instance; } public ExamplePlugin(@Nonnull JavaPluginInit init) { super(init); LOGGER.atInfo().log("Hello from " + this.getName() + " version " + this.getManifest().getVersion().toString()); } @Override protected void setup() { instance = this; LOGGER.atInfo().log("Setting up plugin " + this.getName()); this.exampleBlockComponentType = this.getChunkStoreRegistry().registerComponent(ExampleBlock.class, "ExampleBlock", ExampleBlock.CODEC); } override protected void start() { this.getChunkStoreRegistry().registerSystem(new ExampleSystem()); this.getChunkStoreRegistry().registerSystem(new ExampleInitializer()); } public ComponentType getExampleBlockComponentType() { return this.exampleBlockComponentType; } } ``` -------------------------------- ### Repository Structure Example Source: https://hytalemodding.dev/en/docs/wiki/6-github Illustrates the expected file structure for documentation within a GitHub repository intended for wiki sync. ```text my-repo/ └── docs/ ├── intro.md ├── installation.md └── usage.md ``` -------------------------------- ### Command to Spawn Instance Source: https://hytalemodding.dev/en/docs/guides/plugin/instances An example command implementation for spawning a new instance from a template. It retrieves player and world context, determines a return point, and then executes the instance spawning logic. ```java public class ExampleSpawnInstanceCommand extends CommandBase { private final RequiredArg nameArg; public ExampleSpawnInstanceCommand() { super("spawninstance", "Spawns a new instance from a template"); this.nameArg = this.withRequiredArg("name", "The name of the new instance", ArgTypes.STRING); } @Override protected void executeSync(@Nonnull CommandContext ctx) { UUID playerUUID = ctx.sender().getUuid(); PlayerRef playerRef = Universe.get().getPlayer(playerUUID); World world = Universe.get().getWorld(playerRef.getWorldUuid()); ISpawnProvider spawnProvider = world.getWorldConfig().getSpawnProvider(); Transform returnPoint = spawnProvider != null ? spawnProvider.getSpawnPoint(world, playerRef.getUuid()) : new Transform(); world.execute(() -> { World instanceWorld = InstancesPlugin.get().spawnInstance(this.nameArg.get(ctx), world, returnPoint).join(); Universe.get().sendMessage(Message.raw("Instance spawned: " + instanceWorld.getName())); }); } } ``` -------------------------------- ### Verify Java Installation Source: https://hytalemodding.dev/en/docs/guides/plugin/setting-up-env Check your installed Java version by running this command in your terminal. This confirms that the JDK has been successfully installed and is accessible. ```bash java -version ``` -------------------------------- ### Create and Use a Basic HashMap Source: https://hytalemodding.dev/en/docs/guides/java-basics/11-hashmaps Demonstrates creating a HashMap with String keys and Integer values, adding pairs, and retrieving a value by its key. ```java import java.util.HashMap; public class Main { public static void main(String[] args) { // Create a HashMap (String keys, Integer values) HashMap playerLevels = new HashMap<>(); // Add key-value pairs playerLevels.put("Alice", 10); playerLevels.put("Bob", 15); playerLevels.put("Charlie", 8); // Get a value by key int aliceLevel = playerLevels.get("Alice"); // 10 System.out.println("Alice is level " + aliceLevel); } } ``` -------------------------------- ### Install OpenJDK 25 via Homebrew on macOS Source: https://hytalemodding.dev/en/docs/guides/plugin/setting-up-env Install OpenJDK 25 on macOS using Homebrew, a package manager for macOS. This command installs the specified JDK version. ```bash brew install openjdk@25 ``` -------------------------------- ### Run Setup Script Source: https://hytalemodding.dev/en/docs/guides/plugin/browsing-serverjar Execute the Python run script to set up the decompiled Hytale server project. Ensure HytaleServer.jar is in the root directory or its path is set via an environment variable. ```bash python run.py setup ``` -------------------------------- ### Create and Use Item Objects in Java Source: https://hytalemodding.dev/en/docs/guides/java-basics/07-introduction-oop Demonstrates how to instantiate an Item object and call its methods like 'use' and 'getTotalWeight'. ```java public class Main { public static void main(String[] args) { Item potion = new Item("Health Potion", "Consumable", 5, 0.5); potion.use(); // Used Health Potion. Remaining: 4 System.out.println("Total weight: " + potion.getTotalWeight()); // 2.0 } } ``` -------------------------------- ### Install OpenJDK 25 via apt on Linux Source: https://hytalemodding.dev/en/docs/guides/plugin/setting-up-env Install OpenJDK 25 on Debian-based Linux distributions (like Ubuntu) using the system's package manager. This command updates the package list and installs the JDK. ```bash sudo apt update sudo apt install openjdk-25-jdk ``` -------------------------------- ### Define and Execute a Hytale Command with Various Argument Types Source: https://hytalemodding.dev/en/docs/guides/plugin/creating-commands This example demonstrates how to define a command with default, optional, and flag arguments. It shows how to access argument values and context within the execute method. Ensure you have the necessary command context when retrieving argument values. ```java public class HealPlayerCommand extends AbstractTargetPlayerCommand { private final DefaultArg healthArg; private final OptionalArg messageArg; private final FlagArg debugArg; public HealPlayerCommand() { super("healplayer", "Healing a player for an amount of HP (default: 100)"); // Abstract TargetPlayerCommand passes the player that ran the command by default and implements // the use of `--player ` to specify someone else // args this.healthArg = this.withDefaultArg("health", "Amount to heal player", ArgTypes.FLOAT, (float)100, "Desc of Default: 100"); // Or you could do the following making the health value required instead of with a default. // You would need to change the declaration to RequiredArg // this.healthArg = this.withRequiredArg("health", "Amount to heal player", ArgTypes.FLOAT); // Optional args require the user the input `-- ` so the following would require `--message "Good Luck"` this.messageArg = this.withOptionalArg("message", "Message to print while healing", ArgTypes.STRING); // No type needed due to being a bool this.debugArg = this.withFlagArg("debug", "Add debug logs"); } @Override protected void execute(@NonNullDecl CommandContext commandContext, @NullableDecl Ref ref, @NonNullDecl Ref ref1, @NonNullDecl PlayerRef playerRef, @NonNullDecl World world, @NonNullDecl Store store) { if (this.debugArg.get(commandContext) == true) { // <-- See commandContext passed to argument here commandContext.sendMessage(Message.raw("We are debugging")); } // Health is stored in a generic stat map to allowing mods/future content to easily add more stats if desired. EntityStatMap stats = store.getComponent(ref, EntityStatMap.getComponentType()); int healthIdx = DefaultEntityStatTypes.getHealth(); EntityStatValue health = stats.get(healthIdx); float missing = health.getMax() - health.get(); if (this.debugArg.get(commandContext) == true) { // <-- See commandContext passed to argument here commandContext.sendMessage(Message.raw("Missing: " + missing + " health")); commandContext.sendMessage(Message.raw("Adding: " + healthArg.get(commandContext) + " health to ")); commandContext.sendMessage(Message.raw(messageArg.get(commandContext))); commandContext.sendMessage(Message.raw("Input Value: " + healthArg.get(commandContext) + " Default")); commandContext.sendMessage(Message.raw("Default Health Value: "+healthArg.getDefaultValue())); } stats.addStatValue(healthIdx, healthArg.get(commandContext)); // <-- See commandContext passed to argument here } } ``` -------------------------------- ### Install Stripped JAR to Maven Local Repository Source: https://hytalemodding.dev/en/docs/guides/plugin/browsing-serverjar Install the stripped Hytale server JAR into your local Maven repository. ```bash mvn install:install-file -Dfile=hytale-server-stripped.jar -DgroupId="com.hypixel.hytale" -DartifactId=HytaleServer-stripped -Dversion="1.0-SNAPSHOT" -Dpackaging=jar ``` -------------------------------- ### Player Inventory System Example in Java Source: https://hytalemodding.dev/en/docs/guides/java-basics/05-arrays Simulates a player's inventory using a string array, adding items and displaying the inventory status. ```Java String[] inventory = new String[9]; // 9 hotbar slots // Add items inventory[0] = "Diamond Sword"; inventory[1] = "Shield"; inventory[8] = "Food"; // Display inventory for (int i = 0; i < inventory.length; i++) { if (inventory[i] != null) { System.out.println("Slot " + i + ": " + inventory[i]); } else { System.out.println("Slot " + i + ": Empty"); } } ``` -------------------------------- ### Enter Instance Command Source: https://hytalemodding.dev/en/docs/guides/plugin/instances Spawns a new instance with a given name and immediately teleports the player into it. Requires the instance name as an argument. ```java public class ExampleEnterInstanceCommand extends CommandBase { private final RequiredArg nameArg; public ExampleEnterInstanceCommand() { super("enterinstance", "Spawns and enters an instance immediately"); this.nameArg = this.withRequiredArg("name", "The name of the instance", ArgTypes.STRING); } @Override protected void executeSync(@Nonnull CommandContext ctx) { UUID playerUUID = ctx.sender().getUuid(); PlayerRef playerRef = Universe.get().getPlayer(playerUUID); World world = Universe.get().getWorld(playerRef.getWorldUuid()); ISpawnProvider spawnProvider = world.getWorldConfig().getSpawnProvider(); Transform returnPoint = spawnProvider != null ? spawnProvider.getSpawnPoint(world, playerRef.getUuid()) : new Transform(); world.execute(() -> { //World instanceWorld = InstancesPlugin.get().spawnInstance(this.nameArg.get(ctx), world, returnPoint).join(); //InstancesPlugin.teleportPlayerToInstance(playerRef.getReference(), playerRef.getReference().getStore(), instanceWorld, (Transform) null); CompletableFuture worldFuture = InstancesPlugin.get().spawnInstance(this.nameArg.get(ctx), world, returnPoint); InstancesPlugin.teleportPlayerToLoadingInstance(playerRef.getReference(), playerRef.getReference().getStore(), worldFuture, null); }); } } ``` -------------------------------- ### Icon Name Example Source: https://hytalemodding.dev/en/docs/contributing/translate Shows an example of an icon definition. The icon name itself must not be translated as it's a technical identifier. ```yaml icon: Globe ``` -------------------------------- ### Registering a Custom System Source: https://hytalemodding.dev/en/docs/guides/plugin/spawning-entities Register your custom system within the plugin's setup function to enable its functionality for entity management. ```java this.getEntityStoreRegistry().registerSystem(new AddNetworkIdToMyEntitySystem()) ``` -------------------------------- ### Full NPC Spawning Command Example Source: https://hytalemodding.dev/en/docs/guides/plugin/spawning-npcs This command spawns a 'Kweebec Sapling' NPC at the player's location, sets up its inventory with items and armor, and registers the command for use. ```java import com.example.npc.NPCPlugin; // Adjust imports as necessary import hytale.server.plugin.npc.INonPlayerCharacter; import hytale.server.plugin.npc.NPCEntity; // ... other imports public class SpawnNpcCommand extends AbstractPlayerCommand { public SpawnNpcCommand() { // Register the command /npc which will trigger the "spawn npc" action super("npc", "spawn npc"); } @Override protected void execute(@NonNullDecl CommandContext commandContext, @NonNullDecl Store store, @NonNullDecl Ref ref, @NonNullDecl PlayerRef playerRef, @NonNullDecl World world) { // Get the player's current position to spawn the NPC at the same location Vector3d position = playerRef.getTransform().getPosition(); // Define the initial rotation (facing direction) for the NPC Vector3f rotation = new Vector3f(0, 0, 0); // Use the NPCPlugin helper to spawn the NPC. Pair, INonPlayerCharacter> result = NPCPlugin.get().spawnNPC(store, "Kweebec_Sapling", null, position, rotation); if (result != null) { // Successfully spawned Ref npcRef = result.first(); // Retrieve the NPC interface if needed for further interaction INonPlayerCharacter npc = result.second(); // Set up the NPC's inventory and equipment setupNPCInventory(npcRef, store); } } /** * Configures the inventory for the spawned NPC. */ public void setupNPCInventory(Ref npcRef, Store store) { // Retrieve the NPCEntity component to access inventory settings NPCEntity npcComponent = store.getComponent(npcRef, Objects.requireNonNull(NPCEntity.getComponentType())); if (npcComponent == null) return; // Initialize inventory size (e.g., 3 rows, 9 columns, 0 offset) npcComponent.setInventorySize(3, 9, 0); // Add items to the initialized inventory addItemsToNPCInventory(npcComponent.getInventory()); } /** * Adds specific items and armor to the NPC's inventory. */ public void addItemsToNPCInventory(Inventory inventory) { // Add a Thorium Mace to the first slot of the hotbar inventory.getHotbar().addItemStackToSlot((short) 0, new ItemStack("Weapon_Mace_Thorium", 1)); // Equip a Thorium Helmet using the InventoryHelper InventoryHelper.useArmor(inventory.getArmor(), "Armor_Thorium_Head"); // Set the active hotbar slot to the weapon inventory.setActiveHotbarSlot((byte) 0); } } ``` ```java public class MyHytaleMod extends JavaPlugin { @Override protected void setup() { this.getCommandRegistry().registerCommand(new SpawnNpcCommand()); } } ``` -------------------------------- ### Gradle Build Failure: Hytale Not Found Source: https://hytalemodding.dev/en/docs/guides/plugin/build-and-test This error indicates Gradle cannot find the Hytale installation. Ensure the game is installed and the path is correctly configured. ```text FAILURE: Build failed with an exception. * What went wrong: Failed to find Hytale at the expected location. Please make sure you have installed the game. The expected location can be changed using the hytale.home_path property. Currently looking in 'C:\Path\To\Hytale' ``` -------------------------------- ### Basic Third-Person Camera Setup Source: https://hytalemodding.dev/en/docs/guides/plugin/customizing-camera-controls Sets up a basic third-person camera with adjustable zoom distance, perspective, and follow smoothness. Use this for a standard over-the-shoulder view. ```java ServerCameraSettings settings = new ServerCameraSettings(); settings.distance = 10.0f; // Zoom distance from player settings.isFirstPerson = false; // Third-person mode settings.positionLerpSpeed = 0.2f; // Smooth camera follow playerRef.getPacketHandler().writeNoCache( new SetServerCamera(ClientCameraView.Custom, true, settings) ); ``` -------------------------------- ### Framework DecimalConstants Entry Example Source: https://hytalemodding.dev/en/docs/official-documentation/worldgen/technical-hytale-generator/world-structure An example of a DecimalConstants entry within the Framework module. This defines named decimal constants used in world generation. ```json "Framework": [ { "Type": "DecimalConstants", "Entries": [ { "Name": "Base", "Value": 100 } ] } ] ``` -------------------------------- ### PermissionAttachmentSystem Example Source: https://hytalemodding.dev/en/docs/guides/ecs/systems An example of a RefChangeSystem that listens for additions, updates, and removals of the PermissionAttachment component. It accesses entity data to log player UUIDs during these events. ```java public class PermissionAttachmentSystem extends RefChangeSystem { private static final HytaleLogger LOGGER = HytaleLogger.forEnclosingClass(); @Nonnull @Override public ComponentType componentType() { return EntityStoreRegistry.get().getPermissionAttachmentComponentType(); } @Override public void onComponentAdded(@Nonnull Ref ref, @Nonnull PermissionAttachment permissionAttachment, @Nonnull Store store, @Nonnull CommandBuffer commandBuffer) { UUIDComponent component = store.getComponent(ref, UUIDComponent.getComponentType()); UUID playerUuid = component.getUuid(); // PermissionAttachment component was added to a new entity } @Override public void onComponentSet(@Nonnull Ref ref, @Nullable PermissionAttachment oldAttachment, @Nonnull PermissionAttachment newAttachment, @Nonnull Store store, @Nonnull CommandBuffer commandBuffer) { UUIDComponent component = store.getComponent(ref, UUIDComponent.getComponentType()); UUID playerUuid = component.getUuid(); // PermissionAttachment component was updated using replaceComponent or putComponent } @Override public void onComponentRemoved(@Nonnull Ref ref, @Nonnull PermissionAttachment permissionAttachment, @Nonnull Store store, @Nonnull CommandBuffer commandBuffer) { UUIDComponent component = store.getComponent(ref, UUIDComponent.getComponentType()); UUID playerUuid = component.getUuid(); // PermissionAttachment component was removed from an entity } @Nullable @Override public Query getQuery() { return EntityStoreRegistry.get().getPermissionAttachmentComponentType(); } } ``` -------------------------------- ### First Instruction Match Example Source: https://hytalemodding.dev/en/docs/guides/npc-workings/npc-role Illustrates the first instruction match within a nested structure, focusing on a player sensor and body motion. This snippet is evaluated if the initial state sensor matches. ```json "Instructions":[ { "Sensor": { "Type": "Player", "Range": 8, "Filters": [ { "Type": "ItemInHand", "Items": ["Plant_Fruit_Berries_Red"] } ] }, "HeadMotion": { "Type": "Watch" }, "BodyMotion":{ "Type":"Seek", "RelativeSpeed": 0.6, "StopDistance":3 } }, { "Reference": "Component_Instruction_Intelligent_Idle_Motion_Wander" } ] ``` -------------------------------- ### Get HashMap Size and Check if Empty Source: https://hytalemodding.dev/en/docs/guides/java-basics/11-hashmaps Demonstrates using `size()` to get the number of key-value pairs and `isEmpty()` to check if the HashMap contains any entries. ```java HashMap scores = new HashMap<>(); scores.put("Alice", 100); int size = scores.size(); // 1 boolean empty = scores.isEmpty(); // false ``` -------------------------------- ### Get HashMap Values with Default Source: https://hytalemodding.dev/en/docs/guides/java-basics/11-hashmaps Demonstrates retrieving values using `get()`, which returns `null` for non-existent keys, and `getOrDefault()` to provide a fallback value. ```java HashMap scores = new HashMap<>(); scores.put("Alice", 100); int score = scores.get("Alice"); // 100 Integer missing = scores.get("Dave"); // null (doesn't exist) // Get with default value int score2 = scores.getOrDefault("Dave", 0); // 0 (returns default) ``` -------------------------------- ### Query Examples Source: https://hytalemodding.dev/en/docs/guides/ecs/systems Demonstrates how to construct queries to filter entities based on component presence or absence. Use Query.and() for required components and Query.not() for exclusions. ```java // Single component - any entity with PoisonComponent Query.and(poisonComponentType) // Multiple components - entities with both Query.and(poisonComponentType, Player.getComponentType()) // Exclusion - players that aren't dead Query.and(Player.getComponentType(), Query.not(DeathComponent.getComponentType())) ``` -------------------------------- ### KeyedCodec Initialization Source: https://hytalemodding.dev/en/docs/guides/ecs/hytale-ecs-theory Examples of initializing KeyedCodec instances for String and Integer fields using unique identifiers and built-in codecs. ```java KeyedCodec example = new KeyedCodec("ExampleIdForCodec", Codec.STRING); KeyedCodec exampleInt = new KeyedCodec("ExampleIntIdForCodec", Codec.INTEGER); ``` -------------------------------- ### HealthRegenSystem Example Source: https://hytalemodding.dev/en/docs/guides/ecs/systems An example of a DelayedEntitySystem that executes its tick logic at a specified interval (1.0f second in this case) per matching entity. It queries for entities with the Player component. ```java public class HealthRegenSystem extends DelayedEntitySystem { public HealthRegenSystem() { super(1.0f); } @Override public void tick(float dt, int index, @Nonnull ArchetypeChunk archetypeChunk, @Nonnull Store store, @Nonnull CommandBuffer commandBuffer) { // Runs every 1 second per matching entity } @Nonnull @Override public Query getQuery() { return Query.and(Player.getComponentType()); } } ``` -------------------------------- ### Category Configuration Example Source: https://hytalemodding.dev/en/docs/wiki/6-github Shows how to use a meta.json file to configure category titles and publication status for hierarchical documentation. ```json { "title": "My Category", "published": true } ``` -------------------------------- ### PoisonSystem Example Source: https://hytalemodding.dev/en/docs/guides/ecs/systems An example of an EntityTickingSystem that applies poison damage to entities over time. It uses delta time to manage elapsed time and tick intervals, removing the component when expired. ```java public class PoisonSystem extends EntityTickingSystem { private final ComponentType poisonComponentType; public PoisonSystem(ComponentType poisonComponentType) { this.poisonComponentType = poisonComponentType; } @Override public void tick(float dt, int index, @Nonnull ArchetypeChunk archetypeChunk, @Nonnull Store store, @Nonnull CommandBuffer commandBuffer) { PoisonComponent poison = archetypeChunk.getComponent(index, poisonComponentType); Ref ref = archetypeChunk.getReferenceTo(index); poison.addElapsedTime(dt); if (poison.getElapsedTime() >= poison.getTickInterval()) { poison.resetElapsedTime(); Damage damage = new Damage(Damage.NULL_SOURCE, DamageCause.OUT_OF_WORLD, poison.getDamagePerTick()); DamageSystems.executeDamage(ref, commandBuffer, damage); poison.decrementRemainingTicks(); } if (poison.isExpired()) { commandBuffer.removeComponent(ref, poisonComponentType); } } @Nullable @Override public SystemGroup getGroup() { return DamageModule.get().getGatherDamageGroup(); } @Nonnull @Override public Query getQuery() { return Query.and(this.poisonComponentType); } } ``` -------------------------------- ### State Transitions with Actions Source: https://hytalemodding.dev/en/docs/guides/npc-workings/npc-states Defines actions to be performed between state transitions. This example clears targets and resets instructions when returning to the 'Idle' state. ```json { "StateTransitions":[ { "$Comment": "Always clear target and reset instructions when going back to idle.", "States": [ { "To": [ "Idle" ], "From": [ ] } ], "Actions": [ { "Type": "ReleaseTarget" }, { "Type": "ResetInstructions" }, { "Type": "PlayAnimation", "Slot": "Status" } ] } ] } ``` -------------------------------- ### Java Infinite While Loop (Bad Example) Source: https://hytalemodding.dev/en/docs/guides/java-basics/04-control-flow-loops An example of an infinite loop where the condition never becomes false due to a forgotten update step. This will cause the program to run indefinitely. ```java int x = 0; while (x < 10) { System.out.println("Stuck!"); // Forgot to increase x! } ``` -------------------------------- ### Basic Property Types Examples Source: https://hytalemodding.dev/en/docs/official-documentation/custom-ui/markup Provides examples of basic property types in Hytale UI markup, including Boolean, Int, Float, String, Char, Color, Objects, and Arrays. ```markup Visible: false; Visible: true; ``` ```markup Height: 20; ``` ```markup Min: 0.2; ``` ```markup Text: "Hi!"; ``` ```markup PasswordChar: "*"; ``` ```markup Background: #ffffff; ``` ```markup Style: (Background: #ffffff) ``` ```markup TextSpans: [(Text: "Hi", IsBold: true)] ``` -------------------------------- ### Create and Use Player Objects Source: https://hytalemodding.dev/en/docs/guides/java-basics/07-introduction-oop This snippet demonstrates how to create instances (objects) of the 'Player' class, set their properties, and call their methods. ```java public class Main { public static void main(String[] args) { // Create objects from the Player class Player player1 = new Player(); player1.name = "Alice"; player1.health = 100; player1.level = 5; Player player2 = new Player(); player2.name = "Bob"; player2.health = 80; player2.level = 3; // Use the objects player1.takeDamage(20); // Alice took 20 damage! player2.takeDamage(15); // Bob took 15 damage! } } ``` -------------------------------- ### BuilderCodec for PoisonComponent Source: https://hytalemodding.dev/en/docs/guides/ecs/hytale-ecs-theory Example of creating a BuilderCodec for a PoisonComponent with 'damagePerTick' and 'poisonName' fields. ```java public class PoisonComponent implements Component { private float damagePerTick; private String poisonName; // Constructors, getters, setters, clone method omitted for brevity public static final BuilderCodec CODEC = BuilderCodec.builder(PoisonComponent.class, PoisonComponent::new) .append( new KeyedCodec("DamagePerTick", Codec.FLOAT), (data, value) -> data.damagePerTick = value, (data) -> data.damagePerTick ) .add() .append( new KeyedCodec("PoisonName", Codec.STRING), (data, value) -> data.poisonName = value, (data) -> data.poisonName ) .add() .build(); } ``` -------------------------------- ### Initialize Array with Values in Java Source: https://hytalemodding.dev/en/docs/guides/java-basics/05-arrays Create an integer array and populate it with initial values directly. ```Java int[] numbers = {10, 20, 30, 40, 50}; ```