### Code Example Source: https://kronnect.com/docs/voxel-play/items-models-api Example C# script demonstrating Voxel Play API usage for placing and highlighting models. ```APIDOC ## Code Example ```csharp using VoxelPlay; public class VoxelCrafter : MonoBehaviour { public ModelDefinition houseModel; void PlaceHouseAtCursor() { var env = VoxelPlayEnvironment.instance; // Raycast to find placement point Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (env.RayCast(new Rayd(ray), out VoxelHitInfo hit, 50f)) { // Show build preview env.ModelHighlight(houseModel, hit.voxelCenter); if (Input.GetMouseButtonDown(0)) { // Build with animation env.ModelPlace( hit.voxelCenter + Vector3d.up, houseModel, buildDuration: 2f, callback: (model, pos) => { env.ShowMessage("House built!"); } ); } } } void SpawnTorch() { var env = VoxelPlayEnvironment.instance; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (env.RayCast(new Rayd(ray), out VoxelHitInfo hit, 20f)) { env.TorchAttach(hit); } } } ``` ``` -------------------------------- ### Voxel Placement Example Source: https://kronnect.com/docs/voxel-play/items-models-api Example script demonstrating how to place a model (house) at the cursor position, including a build preview and confirmation message. ```csharp using VoxelPlay; public class VoxelCrafter : MonoBehaviour { public ModelDefinition houseModel; void PlaceHouseAtCursor() { var env = VoxelPlayEnvironment.instance; // Raycast to find placement point Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (env.RayCast(new Rayd(ray), out VoxelHitInfo hit, 50f)) { // Show build preview env.ModelHighlight(houseModel, hit.voxelCenter); if (Input.GetMouseButtonDown(0)) { // Build with animation env.ModelPlace( hit.voxelCenter + Vector3d.up, houseModel, buildDuration: 2f, callback: (model, pos) => { env.ShowMessage("House built!"); } ); } } } void SpawnTorch() { var env = VoxelPlayEnvironment.instance; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (env.RayCast(new Rayd(ray), out VoxelHitInfo hit, 20f)) { env.TorchAttach(hit); } } } ``` -------------------------------- ### Example: Implementing a Door Script Source: https://kronnect.com/docs/voxel-play/interactive-objects Demonstrates how to create a custom interactive object by inheriting from VoxelPlayInteractiveObject. ```APIDOC ## Example: Door Script ```csharp public class Door : VoxelPlayInteractiveObject { // Override virtual methods to implement door behavior public override void OnPlayerAction() { // Logic to open or close the door Debug.Log("Player interacted with the door!"); } public override void OnPlayerApproach() { // Optional: Logic when player approaches Debug.Log("Player is near the door."); } public override void OnPlayerGoesAway() { // Optional: Logic when player moves away Debug.Log("Player has left the door area."); } } ``` ``` -------------------------------- ### Add Message to Console Source: https://kronnect.com/docs/voxel-play/ui-console-api Use this script to add a "Hello World!" message to the console when the game starts. Ensure VoxelPlayUI is accessible. ```csharp using VoxelPlay; public class MyScript : MonoBehaviour { void Start() { VoxelPlayUI.instance.AddMessage("Hello World!"); } } ``` -------------------------------- ### Get Custom Voxel GameObject Reference Source: https://kronnect.com/docs/voxel-play/faq-voxel-gameobject-ref Use this method to get a reference to an instantiated gameobject. If the custom voxel definition has GPU Instancing enabled, there might not be a gameobject in the scene unless explicitly marked for creation. To change the material, use `GetComponentInChildren().material` to ensure you modify a self-copy. ```csharp GameObject voxelGameObject = env.GetVoxelGameObject(position); ``` -------------------------------- ### Initialize Voxel Play Environment Source: https://kronnect.com/docs/voxel-play/faq-spawn-mobs Verify that the Voxel Play environment is initialized before proceeding with spawning logic. ```csharp VoxelPlayEnvironment env = VoxelPlayEnvironment.instance; if (!env.initialized) return; ``` -------------------------------- ### Get Neighbour of a Voxel Source: https://kronnect.com/docs/voxel-play/faq-neighbour-voxel Retrieves the chunk and index of a neighboring voxel based on specified offsets. ```APIDOC ## GetVoxelIndex ### Description Retrieves the neighbor of a specific voxel by providing the current chunk, voxel index, and coordinate offsets. The method returns the neighbor's chunk and index via out parameters. ### Method C# Method Call ### Parameters - **chunk** (VoxelChunk) - Required - The current chunk containing the voxel. - **voxelIndex** (int) - Required - The index of the current voxel. - **offsetX** (int) - Required - The X-axis offset to the target neighbor. - **offsetY** (int) - Required - The Y-axis offset to the target neighbor. - **offsetZ** (int) - Required - The Z-axis offset to the target neighbor. - **otherChunk** (VoxelChunk) - Required - Out parameter to store the neighbor's chunk. - **otherVoxelIndex** (int) - Required - Out parameter to store the neighbor's voxel index. - **createChunkIfNotExists** (bool) - Optional - If true, forces the creation of a chunk if it does not exist. ### Request Example public bool GetVoxelIndex (VoxelChunk chunk, int voxelIndex, int offsetX, int offsetY, int offsetZ, out VoxelChunk otherChunk, out int otherVoxelIndex, bool createChunkIfNotExists = false) ### Response - **return** (bool) - Returns true if the operation was successful. ``` -------------------------------- ### Voxel Custom Properties Source: https://kronnect.com/docs/voxel-play/voxel-properties-api APIs for setting, getting, and clearing arbitrary key-value properties (float or string) on voxels. ```APIDOC ## VoxelSetProperty (Float by Name) ### Description Sets a float property on a voxel by name. ### Method `void` ### Endpoint `VoxelPlayEnvironment.instance.VoxelSetProperty` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyName** (`string`) - Required - The name of the property. - **value** (`float`) - Required - The float value to set. ``` ```APIDOC ## VoxelSetProperty (Float by ID) ### Description Sets a float property on a voxel by integer ID (faster than string lookup). ### Method `void` ### Endpoint `VoxelPlayEnvironment.instance.VoxelSetProperty` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyId** (`int`) - Required - The integer ID of the property. - **value** (`float`) - Required - The float value to set. ``` ```APIDOC ## VoxelSetProperty (String by Name) ### Description Sets a string property on a voxel. ### Method `void` ### Endpoint `VoxelPlayEnvironment.instance.VoxelSetProperty` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyName** (`string`) - Required - The name of the property. - **value** (`string`) - Required - The string value to set. ``` ```APIDOC ## VoxelSetProperty (String by ID) ### Description Sets a string property by integer ID. ### Method `void` ### Endpoint `VoxelPlayEnvironment.instance.VoxelSetProperty` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyId** (`int`) - Required - The integer ID of the property. - **value** (`string`) - Required - The string value to set. ``` ```APIDOC ## GetVoxelPropertyFloat (by Name) ### Description Gets a float property value. Returns 0 if the property doesn't exist. ### Method `float` ### Endpoint `VoxelPlayEnvironment.instance.GetVoxelPropertyFloat` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyName** (`string`) - Required - The name of the property. ### Response #### Success Response (200) - **returnValue** (`float`) - The float value of the property, or 0 if not found. ``` ```APIDOC ## GetVoxelPropertyFloat (by ID) ### Description Gets a float property by ID. ### Method `float` ### Endpoint `VoxelPlayEnvironment.instance.GetVoxelPropertyFloat` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyId** (`int`) - Required - The integer ID of the property. ### Response #### Success Response (200) - **returnValue** (`float`) - The float value of the property, or 0 if not found. ``` ```APIDOC ## GetVoxelPropertyString (by Name) ### Description Gets a string property value. Returns null if not set. ### Method `string` ### Endpoint `VoxelPlayEnvironment.instance.GetVoxelPropertyString` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyName** (`string`) - Required - The name of the property. ### Response #### Success Response (200) - **returnValue** (`string`) - The string value of the property, or null if not set. ``` ```APIDOC ## GetVoxelPropertyString (by ID) ### Description Gets a string property by ID. ### Method `string` ### Endpoint `VoxelPlayEnvironment.instance.GetVoxelPropertyString` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyId** (`int`) - Required - The integer ID of the property. ### Response #### Success Response (200) - **returnValue** (`string`) - The string value of the property, or null if not set. ``` ```APIDOC ## VoxelClearProperty (by Name) ### Description Removes a specific property from the voxel. ### Method `void` ### Endpoint `VoxelPlayEnvironment.instance.VoxelClearProperty` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyName** (`string`) - Required - The name of the property to remove. ``` ```APIDOC ## VoxelClearProperty (by ID) ### Description Removes a property by ID. ### Method `void` ### Endpoint `VoxelPlayEnvironment.instance.VoxelClearProperty` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. - **propertyId** (`int`) - Required - The integer ID of the property to remove. ``` ```APIDOC ## VoxelClearProperties ### Description Removes all custom properties from the voxel. ### Method `void` ### Endpoint `VoxelPlayEnvironment.instance.VoxelClearProperties` ### Parameters #### Path Parameters - **chunk** (`VoxelChunk`) - Required - The chunk containing the voxel. - **voxelIndex** (`int`) - Required - The index of the voxel within the chunk. ``` -------------------------------- ### Build Wall and Explode with Voxel Play Source: https://kronnect.com/docs/voxel-play/voxel-operations-api Demonstrates placing voxels to build a wall and then applying area damage to simulate an explosion. Defer mesh updates during placement and refresh all chunks at once for efficiency. ```csharp using VoxelPlay; public class VoxelBuilder : MonoBehaviour { void BuildWall() { var env = VoxelPlayEnvironment.instance; VoxelDefinition brick = env.GetVoxelDefinition("Brick"); // Build a 10x5 wall for (int x = 0; x < 10; x++) { for (int y = 0; y < 5; y++) { env.VoxelPlace( new Vector3d(x, y, 0), brick, playSound: false, refresh: false // defer mesh rebuild ); } } // Refresh all chunks at once env.ChunkRedrawAll(); } void Explode(Vector3d center) { var env = VoxelPlayEnvironment.instance; int destroyed = env.VoxelDamage( center, damage: 100, radius: 5, attenuateDamageWithDistance: true, addParticles: true, playSound: true ); Debug.Log($"Destroyed {destroyed} voxels!"); } } ``` -------------------------------- ### Access Voxel Play API and Handle Events Source: https://kronnect.com/docs/voxel-play/programming-guide Demonstrates how to access the VoxelPlayEnvironment singleton, place a voxel, and subscribe to destruction events. ```csharp using VoxelPlay; // Get the singleton instance VoxelPlayEnvironment env = VoxelPlayEnvironment.instance; // Place a voxel VoxelDefinition stone = env.GetVoxelDefinition("Stone"); env.VoxelPlace(new Vector3d(0, 10, 0), stone); // Subscribe to events env.OnVoxelDestroyed += (chunk, voxelIndex) => { Debug.Log("Voxel destroyed!"); }; ``` -------------------------------- ### Basic Voxel Queries Source: https://kronnect.com/docs/voxel-play/voxel-queries-api Provides methods to get voxel information at a specific position and check for the existence of voxels. ```APIDOC ## GetVoxel ### Description Returns the `Voxel` struct at the given world position. ### Method `Voxel` ### Parameters - **position** (`Vector3d`) - Required - The world position to query. - **createChunkIfNotExists** (`bool`) - Optional - Defaults to `true`. Create the chunk if it hasn't been generated yet. - **onlyRenderedVoxels** (`bool`) - Optional - Defaults to `false`. Only return voxels from chunks that have been rendered. ## IsVoxelAtPosition ### Description Returns true if a non-empty voxel exists at the given position. ### Method `bool` ### Parameters - **position** (`Vector3d`) - Required - The world position to check. ## IsEmptyAtPosition ### Description Returns true if the position contains no voxel (empty space). ### Method `bool` ### Parameters - **position** (`Vector3d`) - Required - The world position to check. ## IsWallAtPosition ### Description Returns true if a solid (opaque) block exists at the given position. ### Method `bool` ### Parameters - **position** (`Vector3d`) - Required - The world position to check. ## IsTerrainReadyAtPosition ### Description Returns true if the terrain at the position has been rendered and has a collider ready. ### Method `bool` ### Parameters - **position** (`Vector3d`) - Required - The world position to check. - **includeWater** (`bool`) - Required - Whether to include water in the check. ``` -------------------------------- ### Get Biome and Terrain Information Source: https://kronnect.com/docs/voxel-play/faq-biome-position Methods to retrieve biome definitions and terrain data from the Voxel Play environment. ```APIDOC ## GetBiome(float altitude, float moisture) ### Description Retrieves the biome definition based on specific altitude and moisture levels. ### Parameters - **altitude** (float) - Required - The altitude value. - **moisture** (float) - Required - The moisture value (0..1 range). ## GetBiome(Vector3d position) ### Description Retrieves the biome definition at a specific world position. ### Parameters - **position** (Vector3d) - Required - The world space position. ## GetTerrainInfo(Vector3 position) ### Description Retrieves a HeightMapInfo struct containing terrain data for a given position. ### Parameters - **position** (Vector3) - Required - The world space position. ### Response - **moisture** (float) - A value in the 0..1 range. - **groundLevel** (int) - The altitude of the terrain in world space. - **biome** (BiomeDefinition) - The biome found at that position. ``` -------------------------------- ### Import Qubicle Binary File Source: https://kronnect.com/docs/voxel-play/import-conversion-api Use QubicleImporter.ImportBinary to convert Qubicle binary files into a color array representation. Ensure correct text encoding is specified. ```csharp ColorBasedModelDefinition colorModel = QubicleImporter.ImportBinary(stream, System.Text.Encoding.UTF8); ``` -------------------------------- ### System UI Methods Source: https://kronnect.com/docs/voxel-play/ui-console-api Methods for managing global UI elements like the initialization panel and debug window. ```APIDOC ## Other Methods ### Description Utility methods for toggling system-level UI components. ### Methods - **ToggleInitializationPanel(bool visible, string text, float progress)** (void) - Shows or hides the loading panel. - **ToggleDebugWindow(bool visible)** (void) - Shows or hides the debug window. ``` -------------------------------- ### Voxel Before Place Event Source: https://kronnect.com/docs/voxel-play/events Fired before a voxel is placed. Modify the `voxelDefinition` or `tintColor` ref parameters to change what gets placed. ```csharp event VoxelPlaceEvent OnVoxelBeforePlace(Vector3d position, VoxelChunk chunk, int voxelIndex, ref VoxelDefinition vd, ref Color32 tintColor); ``` -------------------------------- ### Custom UI Implementation Source: https://kronnect.com/docs/voxel-play/custom-ui Guidelines for creating a custom UI by extending the VoxelPlayUI base class. ```APIDOC ## Custom UI Implementation ### Description To provide a custom UI, create a script that derives from the `VoxelPlayUI` base class. This allows you to override specific methods to handle UI interactions while preserving functionality across Voxel Play upgrades. ### Implementation ```csharp public partial class MyCustomUI : VoxelPlayUI { // Override base methods here } ``` ### Overridable Methods - **InitUI()**: Initialize UI elements. - **ToggleConsoleVisibility(bool state)**: Show/hide the command console. - **AddConsoleText(string text)**: Add text to the console. - **AddMessage(string text, float displayTime, bool flash, bool openConsole)**: Display a message. - **HideStatusText()**: Hide the status bar. - **ToggleInventoryVisibility(bool state)**: Show/hide the inventory. - **InventoryNextPage() / InventoryPreviousPage()**: Navigate inventory pages. - **RefreshInventoryContents()**: Refresh inventory items. - **ShowSelectedItem(InventoryItem item) / HideSelectedItem()**: Manage selected item display. - **ToggleInitializationPanel(bool visible, string text, float progress)**: Manage loading/progress UI. - **ToggleDebugWindow(bool visible)**: Show/hide debug information. ``` -------------------------------- ### Get Neighbour Voxel API Method Source: https://kronnect.com/docs/voxel-play/faq-neighbour-voxel Use this method to retrieve the chunk and index of a neighboring voxel based on specified offsets. ```csharp public bool GetVoxelIndex (VoxelChunk chunk, int voxelIndex, int offsetX, int offsetY, int offsetZ, out VoxelChunk otherChunk, out int otherVoxelIndex, bool createChunkIfNotExists = false) ``` -------------------------------- ### Exclude Chunks from Rendering Source: https://kronnect.com/docs/voxel-play/faq Use the OnChunkBeforeCreate event to conditionally prevent chunks from being rendered. This example creates an empty box centered at (0,100,0). ```csharp env.OnChunkBeforeCreate += (Vector3 chunkCenter, out bool overrideDefaultContents, Voxel[] voxels, out bool isAboveSurface) => { Bounds exclusionBox = new Bounds(); exclusionBox.center = new Vector3(0,100,0); exclusionBox.size = new Vector80,80,80); if (exclusionBox.Contains(chunkCenter)) { overrideDefaultContents = true; } else { overrideDefaultContents = false; } isAboveSurface = true; }; ``` -------------------------------- ### Handle Voxel Play Environment Events Source: https://kronnect.com/docs/voxel-play/events Demonstrates how to subscribe to various Voxel Play events to monitor and modify voxel and chunk behavior at runtime. ```csharp using VoxelPlay; public class VoxelEventHandler : MonoBehaviour { void Start() { var env = VoxelPlayEnvironment.instance; // Wait for initialization env.OnInitialized += () => { Debug.Log("Voxel Play ready!"); }; // Track voxel destruction env.OnVoxelDestroyed += (chunk, voxelIndex) => { Vector3d pos = env.GetVoxelPosition(chunk, voxelIndex); Debug.Log($"Voxel destroyed at {pos}"); }; // Modify voxel type or tint color before placement env.OnVoxelBeforePlace += (Vector3d position, VoxelChunk chunk, int voxelIndex, ref VoxelDefinition voxelType, ref Color32 tintColor) => { // Example: force all placed voxels to have a red tint tintColor = new Color32(255, 100, 100, 255); }; // Custom chunk generation env.OnChunkBeforeCreate += (Vector3d chunkCenter, out bool overrideDefaultContents, VoxelChunk chunk, out bool isAboveSurface) => { overrideDefaultContents = false; isAboveSurface = false; // Add custom ore to every chunk after default generation for (int i = 0; i < chunk.voxels.Length; i++) { if (Random.value < 0.001f) { VoxelDefinition ore = env.GetVoxelDefinition("Gold"); chunk.voxels[i].Set(ore); } } }; // Monitor chunk lifecycle env.OnChunkEnterVisibleDistance += (chunk) => { // Load custom data for this chunk }; env.OnChunkReuse += (VoxelChunk chunk, out bool canReuse) => { canReuse = true; // set false to prevent recycling // Save custom data before chunk is recycled }; } } ``` -------------------------------- ### GET /nodes/samplers/height-map Source: https://kronnect.com/docs/voxel-play/terrain-graph-editor Documentation for the Sample Height Map Texture node, which reads values from a 2D noise texture to generate terrain height. ```APIDOC ## GET /nodes/samplers/height-map ### Description Reads a value from a repeating 2D noise texture. The red channel is used as the height value for terrain generation. ### Parameters #### Request Body - **Noise Texture** (Texture2D) - Required - The 2D texture to sample. - **Frequency** (float) - Optional - Multiplier applied to world X/Z coordinates before sampling (default: 0.1). - **Offset** (Vector2) - Optional - X/Z offset added to sampling coordinates. - **Min** (float) - Optional - Lower bound of the remapped output range. - **Max** (float) - Optional - Upper bound of the remapped output range (default: 0.5). ### Response #### Success Response (200) - **output** (float) - The calculated height value based on the formula: `output = sample(texture, x * frequency + offsetX, z * frequency + offsetY) * (max - min) + min` ``` -------------------------------- ### Implement Detail Generator Lifecycle Methods Source: https://kronnect.com/docs/voxel-play/detail-generators Override these methods to handle initialization, area exploration, and background processing logic. ```csharp public override void Init() { ... } ``` ```csharp public override bool ExploreArea(Vector3d currentPosition, bool checkOnlyBorders, long endTime) { ... } ``` ```csharp public override bool DoWork(long endTime) { ... } ``` -------------------------------- ### Create Model Preview Source: https://kronnect.com/docs/voxel-play/items-models-api Creates a semi-transparent preview of the model at the given position. Useful for build placement previews. ```csharp GameObject ModelHighlight(ModelDefinition modelDefinition, Vector3d position) ``` -------------------------------- ### Get Random Float in Range Source: https://kronnect.com/docs/voxel-play/worldrand Generate a random float within a specified min/max range. This can be linked to a seed or position for deterministic generation. ```csharp WorldRand.Range(float min, float max) ``` ```csharp WorldRand.Range(float min, float max, int seed) ``` ```csharp WorldRand.Range(float min, float max, Vector3d position) ``` -------------------------------- ### Get Next Random Value Source: https://kronnect.com/docs/voxel-play/worldrand Obtain the next random value in the sequence within the 0-1 range. This method does not require any specific input. ```csharp WorldRand.GetValue() ``` -------------------------------- ### Load Game via Console Command Source: https://kronnect.com/docs/voxel-play/loading-saving Use the in-game console to load a game state from a specified file. ```text /load filename ``` -------------------------------- ### Get Biome and Terrain Information Source: https://kronnect.com/docs/voxel-play/faq Methods to retrieve biome definitions and terrain height map information based on world position or environmental factors. ```APIDOC ## GetBiome ### Description Retrieves the biome definition at a specific position or based on environmental factors. ### Methods - public BiomeDefinition GetBiome(float altitude, float moisture) - public BiomeDefinition GetBiome(Vector3d position) ## GetTerrainInfo ### Description Retrieves terrain data at a specific position, returning a HeightMapInfo struct. ### Method public HeightMapInfo GetTerrainInfo(Vector3 position) ### Response - **moisture** (float) - Value in the 0..1 range. - **groundLevel** (int) - Altitude of the terrain in world space. - **biome** (BiomeDefinition) - The biome found at that position. ``` -------------------------------- ### Load Game Binary Method Source: https://kronnect.com/docs/voxel-play/loading-saving Loads a saved game from a file. The filename is specified by the saveFilename property. The firstLoad parameter determines if it's a game startup load, and preservePlayerPosition controls whether the player's current position is maintained. ```csharp VoxelPlayEnvironment.instance.LoadGameBinary(firstLoad, preservePlayerPosition); ``` -------------------------------- ### Voxel Placement Methods Source: https://kronnect.com/docs/voxel-play/voxel-operations-api Methods for placing individual voxels with various parameters like tint, rotation, and fill amount. ```csharp void VoxelPlace(Vector3d position, VoxelDefinition voxelType, bool playSound = false, bool refresh = true) ``` ```csharp void VoxelPlace(Vector3d position, VoxelDefinition voxelType, Color tintColor, bool playSound = false, bool refresh = true) ``` ```csharp void VoxelPlace(Vector3d position, Color tintColor, bool playSound = false, bool refresh = true) ``` ```csharp void VoxelPlace(VoxelChunk chunk, int voxelIndex, Color tintColor, bool playSound = false, bool refresh = true) ``` ```csharp void VoxelPlace(Vector3d position, Voxel voxel, bool playSound = false, bool refresh = true) ``` ```csharp void VoxelPlace(Vector3d position, VoxelDefinition voxelType, bool playSound, Color tintColor, float amount = 1f, int rotation = 0, bool refresh = true) ``` -------------------------------- ### Place Models at Runtime Source: https://kronnect.com/docs/voxel-play/faq Creates an array of voxel definitions and places a model in the scene in front of the camera. This can be used with custom voxel definitions defined at runtime. ```csharp int sizeX = 12, sizeY = 12, sizeZ = 12; VoxelDefinition[,,] model = new VoxelDefinition[sizeY, sizeZ, sizeX]; VoxelDefinition vd = env.GetVoxelDefinition (1); for (int y = 0; y < sizeY; y++) { for (int z = 0; z < sizeZ; z++) { for (int x = 0; x < sizeX; x++) { model [y, z, x] = vd; } } } VoxelPlayFirstPersonController fpsController = VoxelPlayFirstPersonController.instance; env.ModelPlace (Camera.main.transform.position + Camera.main.transform.forward * 100, model); ``` -------------------------------- ### Get Chunk Raw Buffer - Voxel Play 3 Source: https://kronnect.com/docs/voxel-play/multiplayer-api Allocates a new byte array to store chunk contents. Use this method in conjunction with GetChunkRawData(). ```csharp public byte[] GetChunkRawBuffer() ``` -------------------------------- ### Get Random Integer in Range Source: https://kronnect.com/docs/voxel-play/worldrand Generate a random integer within a specified min/max range. This can be linked to a position for reproducible results or used as a general-purpose integer range. ```csharp WorldRand.Range(int min, int max, Vector3d position) ``` ```csharp WorldRand.Range(int min, int max, Vector3d position, int shift) ``` ```csharp WorldRand.Range(int min, int max) ``` -------------------------------- ### Create and Place Voxel Definition at Runtime Source: https://kronnect.com/docs/voxel-play/faq-vd-runtime Initializes a new VoxelDefinition instance and registers it with the environment, followed by an optional placement logic using the first-person controller. ```csharp     VoxelDefinition vd = env.GetVoxelDefinition ("Brick");     if (vd == null) {         vd = ScriptableObject.CreateInstance ();         vd.name = "Brick";         vd.renderType = RenderType.Opaque;         vd.textureTop = texture;         vd.textureSide = texture;         vd.textureBottom = texture;         env.AddVoxelDefinition (vd);     }     VoxelPlayFirstPersonController fpsController = VoxelPlayFirstPersonController.instance;     if (fpsController.crosshairOnBlock) {         Vector3 pos = fpsController.crosshairHitInfo.voxelCenter + fpsController.crosshairHitInfo.normal;         env.VoxelPlace (pos, vd);     } ``` -------------------------------- ### ModelBit Custom Properties - Voxel Play 3 Source: https://kronnect.com/docs/voxel-play/model-definition-structure Demonstrates setting and getting custom string or float properties on a ModelBit. Useful for adding metadata to individual voxels. ```csharp SetProperty(string name, string/float value) GetPropertyString(string name) GetPropertyFloat(string name) ``` -------------------------------- ### Place Voxel Model at Runtime Source: https://kronnect.com/docs/voxel-play/faq-place-models Creates a voxel model array and places it in the scene using the ModelPlace method. Ensure the environment is initialized before calling these methods. ```csharp int sizeX = 12, sizeY = 12, sizeZ = 12; VoxelDefinition[,,] model = new VoxelDefinition[sizeY, sizeZ, sizeX]; VoxelDefinition vd = env.GetVoxelDefinition (1); for (int y = 0; y < sizeY; y++) { for (int z = 0; z < sizeZ; z++) { for (int x = 0; x < sizeX; x++) { model [y, z, x] = vd; } } } VoxelPlayFirstPersonController fpsController = VoxelPlayFirstPersonController.instance; env.ModelPlace (Camera.main.transform.position + Camera.main.transform.forward * 100, model); ``` -------------------------------- ### Add Inventory Items via Scripting Source: https://kronnect.com/docs/voxel-play/faq-default-items Use the OnInitialized event to ensure the environment is ready before adding items to the player's inventory. Item definitions are retrieved using GetItemDefinition by category or name. ```csharp VoxelPlayEnvironment env; void Start () { env = VoxelPlayEnvironment.instance; // When Voxel Play is ready, do some stuff... env.OnInitialized += OnInitialized; } void OnInitialized () { // Item definitions are stored in Items folder within the world name folder // Add 3 torches to initial player inventory VoxelPlayPlayer.instance.AddInventoryItem (env.GetItemDefinition (ItemCategory.Torch), 3); // Add a shovel (no need to specify quantity it's 1 unit) VoxelPlayPlayer.instance.AddInventoryItem (env.GetItemDefinition ("Shovel")); // Add a sword VoxelPlayPlayer.instance.AddInventoryItem (env.GetItemDefinition ("Sword")); } ``` -------------------------------- ### Get Terrain Info at Player Position Source: https://kronnect.com/docs/voxel-play/faq-biome-position Retrieves terrain information, including biome, at the player's current position. Ensure VoxelPlayEnvironment and VoxelPlayPlayer instances are accessible. ```csharp VoxelPlayEnvironment env = VoxelPlayEnvironment.instance; Vector3 playerPosition = VoxelPlayPlayer.instance.GetTransform().position; HeightMapInfo terrainInfo = env.GetTerrainInfo (playerPosition); Debug.Log ("Current biome is " + terrainInfo.biome.name); ``` -------------------------------- ### Get Random Value Linked to Position Source: https://kronnect.com/docs/voxel-play/worldrand Retrieve a random value (0-1 range) that is deterministically linked to a specific 3D position. Overloads are available for Vector3, Vector3d, and 2D coordinates. ```csharp WorldRand.GetValue(Vector3 position) ``` ```csharp WorldRand.GetValue(Vector3 position, int shift) ``` ```csharp WorldRand.GetValue(Vector3d position) ``` ```csharp WorldRand.GetValue(double x, double z) ``` -------------------------------- ### IVoxelPlayPlayer Interface - Inventory Methods Source: https://kronnect.com/docs/voxel-play/custom-player These methods provide basic inventory functionality. You can replace or extend them in your custom player class. They handle adding, picking up, selecting, consuming, and querying items. ```csharp void AddInventoryItem (ItemDefinition [] newItems); bool AddInventoryItem (ItemDefinition newItem, float quantity = 1); void PickUpItem (ItemDefinition newItem, float quantity = 1); void UnSelectItem (); bool SetSelectedItem (int itemIndex); bool SetSelectedItem (InventoryItem item); bool SetSelectedItem (VoxelDefinition vd); InventoryItem GetSelectedItem (); List items { get; } int selectedItemIndex { get; set; } List GetPlayerItems (); bool HasItem (ItemDefinition item); InventoryItem ConsumeItem (); void ConsumeItem (ItemDefinition item); float GetItemQuantity (ItemDefinition item); ``` -------------------------------- ### IVoxelPlayPlayer Interface - Combat Methods Source: https://kronnect.com/docs/voxel-play/custom-player These methods implement basic combat functionality, providing data to other scripts. For instance, the `RayHit` method in your character controller uses these to determine damage. ```csharp void DamageToPlayer (int damagePoints); float GetHitDelay (); float GetHitRange (); int GetHitDamage (); int GetHitDamageRadius (); ``` -------------------------------- ### Load Noise Texture - Voxel Play 3 Source: https://kronnect.com/docs/voxel-play/noisetools Loads noise values from a texture. Use this to get noise data into an array for further processing. Returns the noise values and the texture size. ```csharp float[] noiseValues = NoiseTools.LoadNoiseTexture(texture, out int textureSize); ``` -------------------------------- ### Player API Reference Source: https://kronnect.com/docs/voxel-play/player-api Comprehensive documentation for the IVoxelPlayPlayer interface, including properties, methods, and events. ```APIDOC ## Player API ### Description The Player API provides the `IVoxelPlayPlayer` interface for managing player state, inventory, and health in Voxel Play 3. ### Events - **OnItemSelectedChanged**: Triggered when selected item changes. - **OnPlayerGetDamage**: Triggered before damage occurs. - **OnPlayerIsKilled**: Triggered when life reaches zero. - **OnItemAdded**: Triggered when inventory receives new item. - **OnItemConsumed**: Triggered when item is used. - **OnItemsClear**: Triggered when inventory is emptied. ### Properties - **playerName** (string) - Player name - **life** (int) - Current life/health - **totalLife** (int) - Maximum life/health - **hitDelay** (float) - Delay between weapon hits - **hitDamage** (int) - Damage per hit - **hitRange** (float) - Hit range - **hitDamageRadius** (int) - Radius of hit effect - **selectedItemIndex** (int) - Index of currently selected item - **items** (List) - List of available items ### Methods - **GetSelectedItem()**: Returns currently selected item. - **SetSelectedItem(int itemIndex)**: Select item by index. - **DamageToPlayer(int damagePoints)**: Apply damage to player. - **AddInventoryItem(ItemDefinition newItem, float quantity)**: Add item to inventory. - **ConsumeItem()**: Consume one unit of selected item. - **HasItem(ItemDefinition item)**: Check if player has item. ``` -------------------------------- ### Get Voxel Index - Voxel Play 3 Source: https://kronnect.com/docs/voxel-play/model-definition-structure Calculates the linear index for a voxel given its X, Y, and Z coordinates within the model's dimensions. Essential for accessing or setting specific voxels. ```csharp int GetVoxelIndex(int x, int y, int z) ``` -------------------------------- ### Create Model GameObject with Offset and Scale Source: https://kronnect.com/docs/voxel-play/items-models-api Creates a model GameObject with custom position offset and scale. ```csharp GameObject ModelCreateGameObject(ModelDefinition modelDefinition, Vector3 offset, Vector3 scale) ``` -------------------------------- ### Get Noise Value (2D) - Voxel Play 3 Source: https://kronnect.com/docs/voxel-play/noisetools Samples a 2D noise texture at specified coordinates (x, z). This method is fundamental for retrieving noise values for terrain generation or other procedural effects. ```csharp NoiseTools.GetNoiseValue(noiseArray, textureSize, x, z) ``` -------------------------------- ### Get Noise Value (3D) - Voxel Play 3 Source: https://kronnect.com/docs/voxel-play/noisetools Samples a 3D noise texture at specified coordinates (x, y, z). This is useful for volumetric noise applications, such as generating complex internal structures or effects within voxels. ```csharp NoiseTools.GetNoiseValue(noiseArray, textureSize, x, y, z) ``` -------------------------------- ### Define a Custom Input Controller Source: https://kronnect.com/docs/voxel-play/custom-input Create a custom controller by inheriting from VoxelPlayInputController and implementing the required initialization and update methods. ```csharp public class MyController: VoxelPlayInputController { ... } ``` ```csharp bool Initialize (); ``` ```csharp void UpdateInputState (); ``` -------------------------------- ### Extend VoxelPlayEnvironment with C# Partial Class Source: https://kronnect.com/docs/voxel-play/customizing-asset Add custom methods to VoxelPlayEnvironment by creating a new C# file with the same namespace and class name. This allows access to private fields and preserves changes during Voxel Play upgrades. ```csharp namespace VoxelPlay { public partial class VoxelPlayEnvironment : MonoBehavior { public bool MyVoxelDestroy (VoxelChunk chunk, int voxelIndex) { ... your code goes here ... } } } ``` -------------------------------- ### Get Chunk Raw Data - Voxel Play 3 Source: https://kronnect.com/docs/voxel-play/multiplayer-api Writes chunk contents into a provided byte array, utilizing RLE compression. Returns the actual data length. Ensure the byte array is allocated using GetChunkRawBuffer(). ```csharp public int GetChunkRawData(VoxelChunk chunk, byte[] contents, bool includeVoxelProperties = true, bool includeMicroVoxels = true) ``` -------------------------------- ### Basic Player API Usage Source: https://kronnect.com/docs/voxel-play/player-api Demonstrates how to access the VoxelPlayPlayer instance to modify player attributes like total life. ```csharp using VoxelPlay; public class MyScript : MonoBehaviour { void Start() { VoxelPlayPlayer.instance.totalLife = 5; } } ```