In Voxel Play you can disable or enable events using the env.captureEvents property. Disabling events is useful to avoid recursion if you call an API inside an event handler. Always remember to reenable events by setting back captureEvents to true before the event handler ends execution.
The following methods are available:
Chunk methods
public VoxelTerrainChunk GetCurrentChunk ()
Returns the voxel chunk where the player is located
public Vector3 GetChunkPosition (Vector3 position)
public bool GetChunk (Vector3 position, out VoxelChunk chunk, bool forceCreation = false)
Returns the voxel chunk at a given position
public bool ChunkIsInFrustum (VoxelChunk chunk)
Returns true if the chunk is within camera's frustum.
public VoxelTerrainChunk GetChunkUnpopulated (Vector3 position)
Returns the chunk on a given position before it's been populated by the terrain engine. Can be used to fill the chunk with "holes" setting voxel.hasContent = 2. The default terrain generator won't place any voxel on holes.
public void GetChunks (List<VoxelChunk> chunks, bool onlyModified)
Returns all created chunks into the chunks list (must provide an already initialized list, contents will be cleared by the method). The onlyModified argument limit the result to chunks modified by the user.
public Bounds GetChunksBounds ()
Returns the bounds of all currently generated chunks.
public bool ChunkDestroy (Vector3 position)
Clears a chunk given a world space position.
public void ChunkDestroyAll ()
Clears all existing chunks.
public bool DestroyAllVoxels ()
Destroys everything and reloads the world. Similar to ReloadWorld method.
public bool ChunkReset(VoxelChunk chunk)
Clears any user modification on a chunk and regenerates it by invoking the terrain generator again. Also clears the chunk.modified flag.
public bool GetChunkNavMeshIsReady(VoxelChunk chunk)
Returns true if the NavMesh is generated and ready to use on that chunk
public void ChunkRedraw (VoxelChunk chunk, bool includeNeighbours = false, bool refreshLightmap = true, bool refreshMesh = true)
Causes a chunk to be refreshed. Chunk lightmap will be computed again and Its mesh will be generated. Methods that modify chunks content automatically handle chunk refreshes so you should never need to call this method unless you're modifying directly the chunk.voxel array.
If includeNeighbours is set, the 26 surrounding chunks will also be refreshed.
public void ChunkRedrawNeighbours (VoxelChunk chunk, bool refreshLightmap = false, bool refreshMesh = true)
Causes neighbours of a given chunk to be refreshed. The given chunk is not refreshed. This method is useful when you use connected textures for example and need to refresh the neighbours because there're new voxels on the edges of chunks so the connected texture rules are evaluated again.
public void ChunkCheckArea (Vector3 position, Vector3 chunkExtents, bool renderChunks = false)
Ensures chunks within given bounds defined by chunkExtents are generated and optionally rendered (renderChunks = true). This is useful when you need to generate chunks on demand when they are out of view (ie. far chunks). When renderChunks is true, the chunks mesh, colliders and NavMesh will also be generated (if they're enabled in Voxel Play Environment options).
public byte[] GetChunkRawBuffer()
Returns a newly allocated byte array to store contents of a chunk. Use with GetChunkRawData() method:
public int GetChunkRawData(VoxelChunk chunk, byte[] contents, bool includeVoxelProperties = false)
Writes the contents of a chunk (voxels) into the array contents starting at index "baseIndex". The allocation of the byte array should be obtained using GetChunkRawData() method. Contents are packed using RLE compression to reduce memory usage. The method returns the actual data length contained in contents array.
If "includeVoxelProperties" is true, this method will add all user-defined voxel properties to the byte array (those defined by VoxelSetProperty method)
public byte[] SetChunkRawData(VoxelChunk chunk, byte[] contents, int length, bool validate = true, bool includeVoxelProperties = false)
Replaces the contents of a chunk with "contents". Length param determines the length of valid data inside the contents array (because the array can be bigger than the actual data in it; . If validate is set to true, the voxel types will be checked to ensure they correspond to existing voxel definitions. The contents of the byte array should be obtained using GetChunkRawData() method.
If "includeVoxelProperties" is true, this method will also read all user-defined voxel properties from the byte array (those defined by VoxelSetProperty method)
You must call ChunkRedraw(chunk) to update the chunk representation.
Voxel Definitions methods
public List<VoxelDefinition> voxelDefinitions
The list with all available voxel definitions in current world.
Adds a custom voxel definition created at runtime.
Updates internal texture arrays used for the given voxel definition textures and issues a global chunk mesh refresh.
public GetVoxelDefinition(string name)
Return a voxel definition by its name
public GetVoxelDefinition(int index)
Return a voxel definition by its index
voxelDefinitions.Count
Total number of voxel definitions
Voxel methods
Getting voxels:
public Voxel GetVoxel (Vector3 position)
Gets the voxel at a given position. Returns Voxel.Empty if no voxel found.
public void GetVoxels (Vector3 boxMin, Vector3 boxMax, Voxel[,,] voxels)
Returns a copy of all voxels contained in the volume defined by boxMin/boxMax positions. The copy is returned in the supplied voxels array which must be preallocated and have sufficient space. The array distribution is y/z/x. Use SetVoxels to place the returned array at another position in the world. Use GetVoxelIndices if you need to examine contents of an area in a faster way.
public void SetVoxels (Vector3 boxMin, Vector3 boxMax, Voxel[,,] voxels)
Places the voxels included in the voxels array in the volume defined by boxMin/boxMax positions.
public void SetVoxels (Vector3 position, Voxel[,,] voxels)
Places the voxels included in the voxels array at the give position.
public bool GetVoxelIndex (Vector3 position, out VoxelChunk chunk, out int voxelIndex, bool createChunkIfNotExists = true)
Gets the chunk and array index of the voxel at a given position
public bool GetVoxelIndex (VoxelChunk chunk, int voxelIndex, int offsetX, int offsetY, int offsetZ, out VoxelChunk otherChunk, out int otherVoxelIndex, bool createChunkIfNotExists = false)
Gets the neighbour coordinates of a given voxel.
public int GetVoxelIndex (int px, int py, int pz)
Gets the index of a voxel by its local x,y,z positions inside a chunk.
public int GetVoxelIndices (Vector3 boxMin, Vector3 boxMax, List<VoxelIndex> indices, byte minOpaque, byte hasContents)
Returns all visible or empty voxels within a given 3D volume limited by boxMin/boxMax. You must provide a list as the third argument to which this method will write to. Method returns the count of all visible voxels found.
public int GetVoxelIndices (Vector3 center, int radius, List<VoxelIndex> indices, byte minOpaque, byte hasContents)
Returns all visible or empty voxels within a sphere defined by center and radius. You must provide a list as the third argument to which this method will write to. Method returns the count of all visible voxels found.
public int GetVoxelIndices (Vector3 boxMin, Vector3 boxMax, List<VoxelIndex> indices, SDF sdf)
Returns al voxel indices which satisfy the SDF. The sdf argument is a C# function that accepts a world space position and must return a negative value if that position is contained in a desired volume (sphere, torus, cylinder, custom, ...) or zero or greater if it's outside. The sdf function is evaluated for all positions in the area defined by boxMin - boxMax.
The SDF function must conform to the delegate: delegate float SDF(Vector3 worldPosition);
public Vector3 GetVoxelPosition (VoxelChunk chunk, int voxelIndex)
Gets the voxel position in world space coordinates.
public void GetVoxelChunkCoordinates (int voxelIndex, out int px, out int py, out int pz)
Given a voxel index, returns its x, y, z position inside the chunk
public Voxel GetVoxelUnder (Vector3 position, bool includeWater = false)
Returns the voxel under a given position optionally ignoring water.
public VoxelIndex GetVoxelUnderIndex (Vector3 position, bool includeWater = false)
Returns a VoxelIndex struct containing the chunk and voxelIndex in the chunk's voxel array for the voxel below position, optionally ignoring water.
public GameObject GetVoxelGameObject (Vector3 position)
Returns the gameobject of a custom voxel placed in the world. This only works with instantiated custom voxels. If the custom voxel has GPU instancing enabled, this method returns null, as Voxel Play directly renders GPU instanced voxels on the GPU without creating the gameobject (unless its creation is explicitly marked in the voxel definition).
public bool IsVoxelAtPosition (Vector3 position)
Returns true if the given position is not empty.
Placing voxels:
public void VoxelPlace (Vector3 position, VoxelDefinition voxelType, [Color tintColor], [bool playSound])
Places a new voxel on a givel position in world space coordinates. Optionally assign a tint color and/or plays a sound.
public void VoxelPlace (Vector3 position, Color tintColor, bool playSound = true)
Places a new voxel on a givel position in world space coordinates. Uses default voxel (solid) with tint color. Optionally plays a sound.
public void VoxelPlace (List<Vector3> positions, VoxelDefinition voxelType, Color tintColor, List<VoxelChunk> modifiedChunks = null)
Mass place a voxel type on a list of world positions. Optionally assign a tintColor (use Color.white to preserve texture colors) and returns the list of modified chunks.
public void VoxelPlace (List<VoxelIndex> indices, VoxelDefinition voxelType, Color tintColor, List<VoxelChunk> modifiedChunks = null)
Mass place a voxel type on a list of voxel indices. Optionally assign a tintColor (use Color.white to preserve texture colors) and returns the list of modified chunks.
public void VoxelPlace (Vector3 boxMin, Vector3 boxMax, VoxelDefinition voxelType, Color tintColor, List<VoxelChunk> modifiedChunks = null)
Fills a volume with a given voxel definition and tint color. Optionally returns the list of modified chunks.
public void VoxelPlace (Vector3 boxMin, Vector3 boxMax, Voxel[,,] voxels, bool ignoreEmptyVoxels = false)
Fills a volume with the contents of the voxels array. To skip empty positions in the array, set ignoreEmptyVoxels to true.
Destroying voxels:
public bool VoxelDestroy (Vector3 position)
Clears a voxel at the given position.
public VoxelPlaceholder GetVoxelPlaceholder (VoxelChunk chunk, int voxelIndex, bool createIfNotExists = true)
Creates a placeholder for a given voxel. A placeholder is a real gameobject that's created at a given voxel position and acts as a placeholder for special effects (voxel cracks) or to hold specific scripts that are linked to that voxel. When that voxel is destroyed, the placeholder is disabled.
public bool VoxelDamage(Vector3 position, Vector3 hitDirection, int damage, bool addParticles = false, bool playSound = false)
This overload allows you to specify the impact direction and also emit particles and sound.
public bool VoxelDamage(Vector3 voxelCenter, Vector3 point, Vector3 normal, int damage, bool addParticles = false, bool playSound = false)
This overload damages a voxel by passing the center of the voxel, the hit position and the voxel surface normal..
public bool VoxelDamage(VoxelHitInfo hitInfo, int damage, bool addParticles = false, bool playSound = false)
This overload damages a voxel by passing the hitInfo struct data from env.RayCast method.
Hiding voxels and visibility query:
public void VoxelSetHidden (VoxelChunk chunk, int voxelIndex, bool hidden, HideStyle hiddenStyle = HideStyle.DefinedByVoxelDefinition)
Changes the visibility status of a voxel.
public void VoxelSetHidden (List<VoxelIndex> indices, bool hidden, HideStyle hiddenStyle = HideStyle.DefinedByVoxelDefinition)
Changes the visibility status of a list of voxels defined by its indices.
public void VoxelSetHidden (VoxelIndex [] indices, int count, bool hidden, HideStyle hideStyle = HideStyle.DefinedByVoxelDefinition)
Changes the visibility status of a list of voxels defined by its indices (array variant).
public bool VoxelIsHidden (VoxelChunk chunk, int voxelIndex)
Returns the visibility status of a single voxel.
public bool GetVoxelVisibility (VoxelChunk chunk, int voxelIndex)
Returns true if the specified voxel has content and is visible from any of the 6 surrounding faces.
Storing/reading custom voxel data:
Clears property "propertyName" for a given voxel.
Clears all properties of a specific voxel.
Other:
MicroVoxels methods (Voxel Play 3 beta)
MicroVoxelDestroy(Vector3d position)
Removes a single microvoxel at the given position. The size of microvoxel removed is determined by the Voxel Play Environment MicroVoxels Size setting.
MicroVoxelDestroy(ref VoxelHitInfo hitInfo, int size, float probability = 1f)
Removes microvoxels inside the volume defined by "size" at the hitInfo.center position. The hitInfo struct should also inform the normal so the volume is aligned with that face. The probability parameter can be set to a lower value (0-1) to remove random microvoxels or leave it to 1 to remove all microvoxels inside the volume.
MicroVoxelPlace(Vector3d position, VoxelDefinition voxelType, Color tintColor = default, int rotation = 0)
Places a single microvoxel at the given position. The voxelType property specifies the voxel definition that should be used if there's no voxel set at that position yet (same for tintColor and rotation). Otherwise, these parameters are ignored and the existing voxel type, tint color and rotation are used (microVoxels only determine voxel shape, not type, color or rotation).
MicroVoxelPlace(ref VoxelHitInfo hitInfo, int size, VoxelDefinition voxelType, Color tintColor = default, int rotation = 0)
Fills the volume defined by size and hitInfo.center with microvoxels. The voxelType property specifies the voxel definition that should be used if there's no voxel set at that position yet (same for tintColor and rotation). Otherwise, these parameters are ignored and the existing voxel type, tint color and rotation are used (microVoxels only determine voxel shape, not type, color or rotation).
IsMicroVoxelAtPosition(VoxelChunk chunk, int voxelIndex)
IsMicroVoxelAtPosition(Vector3d position)
Returns true if there's a microvoxel at the given position.
Boundsd GetMicroVoxelBounds(ref VoxelHitInfo hitInfo, int microVoxelSize, float padding = 0)
Returns the bounds defined by hitInfo.center and microVoxelSize, aligned to hitInfo.normal.
Model Definition methods
ModelDefinition.Create(...)
Model definitions can be created using the constructor tool when in playmode or using the static Create utility methods of the ModelDefinition class.
public void ModelPlace (Vector3d position, ModelDefinition model | VoxelDefinition array | colors array, buildDuration...)
Takes all voxels included in a model or colors in the array and put them on the desired place. Each entry in the given model matches 1 voxel in world space.
When placing a model, ModelPlace can return the list of visible voxels included in that model - pass a List<VoxelIndex> as a third argument to get the indices.
public ModelDefinition ModelWorldCapture (Bounds bounds)
Captures the contents of the world inside the given bounds and returns a new Model Definition with those contents.
public GameObject ModelCreateGameObject (ModelDefinition model, Vector3 offset, Vector3 scale, bool useTextures = true, bool useNormalMaps = true)
Returns a gameobject representation of the given model definition. Offset and scale are applied to the gameobject vertices positions. By default, existing voxel definitions textures and normal maps will be used to create a new texture array assigned to the resulting material. Check demo scene 6 for an example.
Voxel Objects
public GameObject VoxelCreateGameObject (Color32[] colors, int sizeX, int sizeY, int sizeZ, Vector3 offset, Vector3 scale)
Creates a voxel gameobject from a colors array with optimal vertex count. The colors array must follow a Y/Z/X distribution and its dimensions must match sizeX/sizeY/sizeZ parameters.
Offset and Scale are optional and defines the resulting mesh center offset and scale.
Note that ModelPlace method creates a voxel per color in the array, while VoxelCreateGameObject creates a single mesh and gameobject. This method is useful to create custom items with voxel appearance.
Terrain/Water methods
public float GetHeight (Vector3 position)
Gets the highest voxel position under a given location (includes terrain and any other voxel object, like trees)
public float GetTerrainHeight (Vector3 position, bool includeWater = true)
Gets the terrain height under a given position
public HeightMapInfo GetTerrainInfo (Vector3 position)
Gets the terrain data on a given position
public float GetVoxelAmbientLight (Vector3 position)
Gets the computed light amount at a given position in 0..1 range
public void AddWaterFlood (Vector3 waterPos, VoxelDefinition waterVoxel, int lifeTime = 24);
Starts water flooding at a certain position. Lifetime value is used to avoid infinite flooding.
public bool IsTerrainReadyAtPosition (Vector3 position);
Returns true there's some chunk below the given position which has colliders or have been rendered.
public bool IsWaterAtPosition (Vector3 position);
Returns true if there's a water voxel at a given position.
public float GetWaterDepth (Vector3 position);
Returns the amount of water at a given position (depth of water or vertical amount of water).
public bool IsWallAtPosition (Vector3 position);
Returns true if there's a solid (fully opaque) voxel at a given position.
public bool IsEmptyAtPosition (Vector3 position);
Returns true if there is no voxel at the position.
public bool enableWaterFlood;
Session only flag that allows you to toggle water flood on/off. Disabling water flood allows you to paint "cascades". Example.
Raycasting methods
These method returns additional information in the VoxelhitInfo struct like the voxel center position and voxel type (see below).
public bool RayHit (Ray ray, int damage, float maxDistance = 0, int damageRadius = 1)
Casts a ray and applies given damage to any voxel impacted in the direction. If damage radius is greater than 1, nearby voxels will also be affected.
public bool RayHit (Vector3 origin, Vector3 direction, int damage, float maxDistance = 0, int damageRadius = 1)
Casts a ray and applies given damage to any voxel impacted in the direction.If damage radius is greater than 1, nearby voxels will also be affected.
public bool RayHit (Vector3 origin, Vector3 direction, int damage, out VoxelHitInfo hitInfo, float maxDistance = 0, int damageRadius = 1)
Casts a ray and applies given damage to any voxel impacted in the direction. If damage radius is greater than 1, nearby voxels will also be affected.
public bool RayCast (Ray ray, out VoxelHitInfo hitInfo, float maxDistance = 0, byte minOpaque = 0)
Raycasts in the direction of the ray. The minOpaque argument specifies the minimum opaque factor for the ray to stop (grass has opaque = 0, water = 2, cutout/tree leaves=3, opaque voxels=15).
public bool RayCast (Vector3 origin, Vector3 direction, out VoxelHitInfo hitInfo, float maxDistance = 0, byte minOpaque = 0)
Raycasts from a given origin and direction. The minOpaque argument specifies the minimum opaque factor for the ray to stop (grass has opaque = 0, water = 2, cutout/tree leaves=3, opaque voxels=15).
public VoxelHitInfo lastHitInfo;
Returns information on the last voxel hit.
VoxelHitInfo fields description:
- point: the world space position of the hit. Note that the hit position is always on the edge of a voxel and cannot be used to retrieve the voxel at that position. For example, when casting a ray downwards and hitting a voxel whose center is (x=0, y=26.5, z=0), the point position would be (x = 0, y=27.0, z=0) which corresponds with the top face of the cube. However if you use GetVoxelIndex() and use that position (x=0,y=27.0,z=0), it will return the voxel on top because the next voxel is at 27. Use voxelCenter instead which returns the center of the voxel hit.
- voxelCenter: the center of the voxel hit in world space. Use this position when calling GetVoxelIndex or other methods that require a position.
- distance: the distance to the hit surface.
- sqrDistance: distance * distance.
- voxelIndex: the index of the voxel.
- chunk: the chunk where the voxel is.
- normal: the normal of the voxel at the hit position.
- collider: the collider of the gameobject or voxel if it exists.
- placeholder: the voxel placeholder if the voxel is dynamic or custom type with "Create GameObject" enabled.
Inventory/items/object methods
public ItemDefinition[] allItems
Gets an array with all the available world voxel definitions
public ItemDefinition GetItemDefinition(category, voxelType)
Gets an item definition based on the category and voxel type options
public ItemDefinition GetItemDefinition(string name)
Gets an item definition by name
public GameObject TorchAttach(hitInfo)
Adds a torch on certain position. A hitinfo struct must be provided which includes the exact position and orientation of the torch. You can reuse the crosshairHitInfo public property of the Voxel
PlayFirstPersonController component (VoxelPlayFirstPersonController.instance.crosshairHitInfo). This method returns the gameobject of the torch itself.
public void TorchAttach(hitInfo)
Removes a torch. You need to pass the chunk where the torch is located and the gameobject of the torch itself.
public GameObject ItemThrow(position, direction, velocity, itemDefinition)
Throws a new item from position towards direction with velocity.
public GameObject ItemSpawn(itemDefinition, position, quantity)
Drops an amount of the same item definition on a given position.
Misc functions
public void ParticleBurst(position, style, count, intensity, ...);
public float GetVoxelAmbientLight(position, out chunk, out voxelIndex);
public void GetVoxelIndices(List<Vector3d> positions, List<VoxelIndex> indices);
public void SetSunRotation(Quaternion rotation);
public void ShowMessage (text, displayDuration, flashEffect);
Adds a message to the UI with optional duration and flash effect.
playerGameObject;
Returns a reference to the player gameobject (the gameobject that has the CharacterController script attached).
lastMessage;
Returns the last message added to the console.
Load/Save/Initialization functions
public void ReloadWorld()
Destroyes everything and reloads current assigned world
public void Redraw()
Redraws all chunks. This method is called by the system when some visual property is changed (ie. GI or Ambient Occlusion)
public void ReloadTextures ()
Reloads all world textures
public bool LoadGameBinary(bool firstLoad, bool preservePlayerPosition, VoxelDefinition fallbackVoxelDefinition)
Loads saved game specified by the saveFilename property of VoxelPlayEnvironment component. Use firstLoad = true if this saved game is used as the starting map, otherwise pass "false" if player is just loading a saved game. The "preservePlayerPosition" allows you to keep player position and orientation when the saved game is loaded (default = false).
The fallbackVoxelDefinition is optional and let you specify a substitute for any missing voxel definition.
public bool SaveGameBinary()
Saves the game into "saveFilename" (property of VoxelPlayEnvironment. Returns true if success.
Saved games are stored inside the Worlds/worldname/SavedGame folders when running inside Unity Editor. In a real build, saved games are stored in Application.persistentDataPath + "/VoxelPlay" folder.
public byte[] SaveGameToByteArray ()
Returns the world encoded in a byte array.
public string SaveGameToBase64 ()
Returns the world in a base-64 encoded string.
public bool LoadGameFromByteArray (byte[] saveGameData, bool preservePlayerPosition, bool clearScene, VoxelDefinition fallbackVoxelDefinition)
Loads game world from a byte array optionally preserving current player position. If you set clearScene to false, existing chunks will be preserved and only modified chunks will be considered (modified chunks in the scene not present in the saved file data will be reseted to default contents). The fallbackVoxelDefinition is optional and let you specify a substitute for any missing voxel definition.
public bool LoadGameFromBase64 (string saveGameData, bool preservePlayerPosition, bool clearScene, VoxelDefinition fallbackVoxelDefinition)
Loads game world from a base-64 encoded string optionally preserving current player position. If you set clearScene to false, existing chunks will be preserved and only modified chunks will be considered (modified chunks in the scene not present in the saved file data will be reseted to default contents). The fallbackVoxelDefinition is optional and let you specify a substitute for any missing voxel definition.
public void SetBuildMode (bool buildMode)
Sets or cancel build mode
Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article