Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
using UnityEngine;
public class TerrainDetector
private TerrainData terrainData;
private int alphamapWidth;
private int alphamapHeight;
private float[,,] splatmapData;
private int numTextures;
public TerrainDetector()
terrainData = Terrain.activeTerrain.terrainData;
alphamapWidth = terrainData.alphamapWidth;
alphamapHeight = terrainData.alphamapHeight;
splatmapData = terrainData.GetAlphamaps(0, 0, alphamapWidth, alphamapHeight);
numTextures = splatmapData.Length / (alphamapWidth * alphamapHeight);
private Vector3 ConvertToSplatMapCoordinate(Vector3 worldPosition)
Vector3 splatPosition = new Vector3();
Terrain ter = Terrain.activeTerrain;
Vector3 terPosition = ter.transform.position;
splatPosition.x = ((worldPosition.x - terPosition.x) / ter.terrainData.size.x) * ter.terrainData.alphamapWidth;
splatPosition.z = ((worldPosition.z - terPosition.z) / ter.terrainData.size.z) * ter.terrainData.alphamapHeight;
return splatPosition;
public int GetActiveTerrainTextureIdx(Vector3 position)
Vector3 terrainCord = ConvertToSplatMapCoordinate(position);
int activeTerrainIndex = 0;
float largestOpacity = 0f;
for (int i = 0; i < numTextures; i++)
if (largestOpacity < splatmapData[(int)terrainCord.z, (int)terrainCord.x, i])
activeTerrainIndex = i;
largestOpacity = splatmapData[(int)terrainCord.z, (int)terrainCord.x, i];
return activeTerrainIndex;

This comment has been minimized.

Copy link

@ziplock9000 ziplock9000 commented Mar 20, 2019

At Line 17 you call GetAlphaMaps and cache the data into a float array. Is there no way to directly access the data within the terrain instead of duplicating some of the data?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.