Procedural terrain generation does not copy splatmaps

I am developing a game that uses chunk based procedural terrain generation using Unity. My terrain needs to be splatmapped at runtime, so I worked out an algorithm for that.

I use a "chunk" prefab which is created every time the world generator decides to create a new chunk. Each piece has a terrain component as well as my script for doing splatmapping (and generating height in the future). The problem is that when instantiating the prefab, the prefab still uses the same TerrainData object containing heights and splatmaps, so every change in one piece also affects the others.

I found that I could instantiate terrainData from the prefab to clone it and it solved half of the problem. Now I can change heightmaps independently, but splatmaps still seem to be 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. AlphamapTextures is a readonly array and changing its elements doesn't seem to do anything (I get the same output files as in debug.png)

I know I can use reflection and force reallocation of the alpha map, but I hope there is a better way to do this. If not, it is a unity that creates a flaw or error.

Thanks for any answers.

+3


source to share





All Articles