TerrainLayer at runtime

I am trying to instantiate a terrain and create a layer for that terrain to render a texture.

There doesn’t seem to be a lot of documentation on this as I have searched for a while now and seem to find mostly splats which are deprecated.


TerrainLayer[] terrainTexture = new TerrainLayer[1];
terrainTexture[0] = new TerrainLayer();
terrainTexture[0].diffuseTexture = (Texture2D)Resources.Load("Assets/Textures/Texture.jpg");
_TerrainData.terrainLayers = terrainTexture;

This is what I currently have. It seems to create the layer, but it does not associate the picture with the diffuse texture. I read about there being permissions that you have to modify with the importing of the texture, but I didn’t see those setting in the inspector or anywhere else.

I read from various articles that the texture should be in a folder called “resources” within the root of the project folder. That didn’t work for me neither did trying to reference it in the Assets folder.

I also tried to debug.log the layer information in the update method after manually creating a layer with a texture. It output “terrainTexture,” but I was unsure how to make it spit out anything more specific. I’m not sure if that’s something that you can actually do.

@jmhutchins
I encountered a similar issue with creating and assigning materials via script. I think adding this line right before you assign it to your terrain data may help.

AssetDatabase.CreateAsset(terrainTexture, "Assets/");

@jmhutchins
if something similar to what you said, but I have realized that if the asset does not exist then it is not possible that something like this will remain detected, it has worked for me with the terrain layers
add this line adapting it to your situation and assign name to your layer…

code:

createdLayer.name = “test1”;
UnityEditor.AssetDatabase.CreateAsset (createdLayer, “Assets / location of your new layers/” + createdLayer.name + “. Terrainlayer”);