I'm developing a game that is using procedural terrain generation based on chunks using Unity. My terrain has to be splatmapped in runtime, so I've developed an algorithm to do that.
I use "chunk" prefab, that is instantiated every time the world generator decides to create new fragment. Each chunk has a terrain component as well as my script to perform splatmapping (and height generation in the future). The problem is, that when I instantiate the prefab, the prefab is still using same TerrainData object containing heights and splatmaps, so every change in one chunk also influences others.
I've found that I can instantiate terrainData from the prefab to clone it and it solved half of the problem. Now I can change heightmaps independently, but the splatmaps seem still connected.
void Start()
{
map = GetComponentInParent<MapGenerator>();
terrain = GetComponent<Terrain>();
//Copy terrain data, solves heightmap problems
terrain.terrainData = GameObject.Instantiate(terrain.terrainData);
//Try to generate new splatmaps
for (int i = 0; i < terrain.terrainData.alphamapTextures.Length; i++)
{
//Debug before changing
File.WriteAllBytes(Application.dataPath + "/../SPLAT_" + i + ".png", terrain.terrainData.alphamapTextures[i].EncodeToPNG());
//Try to change
terrain.terrainData.alphamapTextures[i] = new Texture2D(terrain.terrainData.alphamapHeight, terrain.terrainData.alphamapWidth);
//Debug after changing
File.WriteAllBytes(Application.dataPath + "/../SPLAT_x" + i + ".png", terrain.terrainData.alphamapTextures[i].EncodeToPNG());
}
//Calculate chunk offset
offset = new Vector2(transform.localPosition.x * (terrain.terrainData.alphamapHeight / terrain.terrainData.size.x),
transform.localPosition.z * (terrain.terrainData.alphamapWidth / terrain.terrainData.size.z));
//Splatting usually happens here
//SplatMap();
}
Unfortunately, this piece of code doesn't work. The alphamapTextures is a readonly array and changing its elements seems to do nothing (I get same output files in both debug .pngs)
I know I can use reflection and force the alphamapTextures reallocation, but I hope that there is a better way to do this. If not, thats unity desing flaw or a bug.
Thank you for any replies.