Items & Models

advanced scripting

Voxel Play 4 · Scripting / API

Class: All members on this page belong to VoxelPlayEnvironment. Access via VoxelPlayEnvironment.instance.

Item Definitions

ItemDefinition GetItemDefinition(ItemCategory category, VoxelDefinition voxelType = null)

Returns the item definition for the given category and optional voxel type.

ItemDefinition GetItemDefinition(ItemCategory category, string objName)

Returns the item definition matching the category and object name.

ItemDefinition GetItemDefinition(string name)

Returns the item definition by name.

Item Spawning

Spawned items can carry a persistent property bag that survives drop, pickup, inventory and savegames: use Item.SetProperty(int id, float value, string text = null) and Item.TryGetProperty(int id, out VoxelProperty value) on the spawned Item component. ItemSpawn and ItemThrow accept an optional FastHashSet<VoxelProperty> properties argument, and PickUpItem / AddInventoryItem offer overloads carrying the bag.

GameObject ItemThrow(Vector3d position, Vector3 direction, float velocity, ItemDefinition itemDefinition)

Throws an item as a physics projectile from the given position. Returns the created GameObject.

direction
Throw direction (will be normalized).
velocity
Initial speed of the thrown item.
GameObject ItemSpawn(string itemDefinitionName, Vector3d position, int quantity = 1)

Spawns an item at the given world position. The item appears as a pickup in the world.

quantity
Number of items in the stack.

Torches

GameObject TorchAttach(VoxelHitInfo hitInfo, ItemDefinition torchDefinition = null, bool refreshChunks = true)

Places a torch at the location specified by a raycast hit. The torch is oriented based on the hit normal. Returns the torch GameObject.

torchDefinition
Torch item definition. If null, uses the one returned by GetDefaultTorchDefinition.
refreshChunks
Immediately refresh chunk lighting to include the new torch.
GameObject TorchAttach(Vector3d worldPos, Vector3 normal, ItemDefinition torchDefinition = null, bool refreshChunks = true)

Places a torch at a specific position with the given surface normal for orientation.

void TorchDetach(VoxelChunk chunk, GameObject gameObject)

Removes a torch from the world.

void TorchDetach(VoxelChunk chunk, int lightVoxelIndex)

Removes the torch registered on a lit cell and clears its light, whether or not the torch prefab has been instantiated. Use it when you know where the torch is but not its GameObject, for example torches restored from a savegame whose wall chunk has not loaded yet.

chunk
Chunk that contains the lit cell.
lightVoxelIndex
Index of the lit cell inside that chunk: the empty cell in front of the wall voxel, that is the wall voxel position plus the torch normal. It may belong to a different chunk than the wall voxel.
ItemDefinition GetDefaultTorchDefinition()

Returns the first item of category Torch known to the world, or null if there is none. Items listed in the World Definition come first, then the player items and the items found in the Resources folders. TorchAttach uses it when no torch definition is given, and the World Editor Torch tool preselects it.

Model Placement

A model bit that carries an empty microvoxel map is treated as having no microvoxels of its own, so the shape declared on its Voxel Definition is used instead. Models captured from the world with the World Editor Capture tool store such empty fillers for their solid cells; without this fallback those cells would be placed as plain cubes and the model would lose its shaped voxels (stairs, fences, plants).
void ModelPlace(Vector3d position, ModelDefinition model, int rotationDegrees = 0, float colorBrightness = 1f, bool fitTerrain = false, List<VoxelIndex> indices = null, ModelPlacementAlignment alignment = ModelPlacementAlignment.Centered, bool previewMode = false, bool skipEmptyVoxels = false, bool clearInside = false)

Places a voxel model at the given position instantly.

rotationDegrees
Rotation in degrees (0, 90, 180, or 270).
colorBrightness
Color brightness multiplier.
fitTerrain
Adjust the model's vertical position to match terrain height.
indices
Optional output list of all voxel indices placed by the model.
alignment
Where the given position sits inside the model bounds.
previewMode
Places the model without marking the affected chunks as modified, used by the World Editor preview.
skipEmptyVoxels
Leaves the existing world untouched wherever the model has an empty bit, so the model is stamped over the terrain instead of replacing the whole volume.
clearInside
Also clears the interior of the model as it is placed, so terrain, vegetation or water already present does not remain inside it. In every column covered by the model, voxels below the top of the model are removed, including the space under overhangs. Ignored when skipEmptyVoxels is true, since the two options ask for opposite behaviours. The model asset is never modified: the interior bits are computed on a cached copy. If you edit the bits of a model definition by code, call ModelInvalidateFilledBits to drop that cache.
void ModelPlace(Vector3d position, ModelDefinition model, out Boundsd bounds, int rotationDegrees = 0, float colorBrightness = 1f, bool fitTerrain = false, List<VoxelIndex> indices = null, ModelPlacementAlignment alignment = ModelPlacementAlignment.Centered, bool previewMode = false, bool skipEmptyVoxels = false, bool clearInside = false)

Places a model and outputs the world-space bounds of the placed model. Same options as the overload above.

void ModelPlace(Vector3d position, ModelDefinition model, float buildDuration, int rotationDegrees = 0, float colorBrightness = 1f, bool fitTerrain = false, VoxelModelBuildEndEvent callback = null, ModelPlacementAlignment alignment = ModelPlacementAlignment.Centered, bool previewMode = false, bool skipEmptyVoxels = false, bool clearInside = false)

Places a model with an animated build effect over the specified duration. Same options as the instant overload.

buildDuration
Time in seconds for the build animation.
callback
Optional callback invoked when the build completes.
void ModelPlace(Vector3d position, Color[,,] colors)

Places a model defined as a 3D color array. Each non-transparent color becomes a colored voxel.

void ModelPlace(Vector3d position, VoxelDefinition[,,] voxels, Color[,,] colors = null)

Places a model defined as a 3D array of voxel definitions with optional per-voxel colors.

void ModelPlace(Vector3d position, Voxel[,,] voxels, bool useUnpopulatedChunks)

Places a model from a raw 3D voxel array.

void ModelPlace(VoxelChunk chunk, List<ModelBit> bits)

Places model bits directly into a chunk. Low-level method for custom model loading.

void ModelFillInside(ModelDefinition model)

Adds empty bits to the interior of the model: every position without a voxel, from the model base up to the topmost voxel of each vertical column, is marked as empty. When the model is placed, those empty bits clear any existing world voxels (terrain, grass, water), so building interiors and underground rooms do not end up filled with terrain. Positions without a bit are left untouched. Modifies the ModelDefinition in place, so call it once (for example from a generator's Init) rather than on every placement.

Model Definition Creation

static ModelDefinition ModelDefinition.Create(int sizeX, int sizeY, int sizeZ)

Creates an empty model definition with the specified dimensions.

static ModelDefinition ModelDefinition.Create(int sizeX, int sizeY, int sizeZ, List<VoxelDefinition> voxelDefinitions, List<MicroVoxels> microVoxels = null)

Creates a model from a flat list of voxel definitions (one per position in XYZ order). Optionally includes microvoxel data per position.

static ModelDefinition ModelDefinition.Create(int sizeX, int sizeY, int sizeZ, List<Voxel> voxels, List<MicroVoxels> microVoxels = null)

Creates a model from a flat list of Voxel structs (extracted from chunks). Optionally includes microvoxel data per position.

static ModelDefinition ModelDefinition.Create(int sizeX, int sizeY, int sizeZ, VoxelDefinition voxelDefinition, List<Color> colors)

Creates a model using a single voxel type with varying per-voxel colors.

ModelDefinition ModelWorldCapture(Bounds bounds, bool captureVoxelTintColor = true)

Captures a region of the live world into a ModelDefinition, including voxel types, colors, microvoxels, properties and light sources.

Model GameObjects

GameObject ModelCreateGameObject(ModelDefinition modelDefinition)

Creates a standalone Unity GameObject from a voxel model definition. Not part of the voxel grid.

GameObject ModelCreateGameObject(ModelDefinition modelDefinition, Vector3 offset, Vector3 scale)

Creates a model GameObject with custom position offset and scale.

GameObject ModelHighlight(ModelDefinition modelDefinition, Vector3d position)

Creates a semi-transparent preview of the model at the given position. Useful for build placement previews.

UI & Messaging

void ShowMessage(string txt, float displayDuration = 4, bool flashEffect = false, bool openConsole = false, bool allowDuplicatedMessage = false, string colorName = null)

Displays a message in the in-game console.

displayDuration
Seconds the message remains visible.
flashEffect
Flash the message for emphasis.
openConsole
Automatically open the console panel.
colorName
HTML color name for the message text.
void ShowError(string errorMessage)

Displays an error message in the console (red text).

void LogMessage(string txt)

Logs a message to the console without displaying it as a popup.

void SetBuildMode(bool buildMode)

Enables or disables the built-in build mode UI, allowing the player to place and remove voxels.

Code Example

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);
        }
    }
}
Was this page helpful?