- Home /
Texture doesn't appear on created through code mesh,Texture disappears when I enter play mode
So, basically I made a code which creates a mesh (quad) and the creation of the mesh works perfectly fine but when I try to add texture to it and seems to be not working for some reason and here's the weird part: I made a GUI button in the inspector (the button is visible in the file component which creates the mesh, and the file is attached to empty), and when the button is pressed I call the build mesh function (the build mesh function also calls the AddTexture function I created at the end). So the button seemed to work fine it created the mesh that I wanted with the texture that I wanted. But when I press play it creates the mesh but adds no texture to the material at all, although it basically supposed to do the very same thing that the inspector button does, since at both situations it calls the build mesh function which calls the add texture function (I had put the build mesh function at the Start function so it could run at the start of the program).
Here's the code for the add texture function which gets called at the end of the build mesh function:
int numTilesPerRow = terrainTiles.width / tileResolution;
int numRows = terrainTiles.height / numTilesPerRow;
int texWidth = size_x * tileResolution;
int texHeight = size_z * tileResolution;
Texture2D texture = new Texture2D(texWidth, texHeight);
Color[][] tiles = ChopTiles();
for (int y = 0; y < size_z; y++)
{
for (int x = 0; x < size_x; x++)
{
Color[] colors = tiles[mapData.GetTileAt(x, y)];
texture.SetPixels(x * tileResolution, y * tileResolution, tileResolution, tileResolution, colors);
}
}
texture.filterMode = FilterMode.Point;
texture.wrapMode = TextureWrapMode.Clamp;
texture.Apply();
mesh_renderer.sharedMaterials[0].mainTexture = texture;
}
NOTES: I work with 1 file with 4 textures so the ChopTiles function just returns an array of array of colors that has the textures I use separately. mapData.GetTilesAt() just returns a number which represents a color. And again the mesh builds perfectly fine, the texture is the only problem. Thanks.