#Avoiding "mesh leak" when setting the UV of my mesh in edit mode

1 messages · Page 1 of 1 (latest)

whole vessel
#

So I'm making a little tilemap system which consists in a mesh renderer + script that allows me to define which part of the map texture (seen in the material at the bottom-right corner) it will render. Everything works but I'm constantly getting this in the log: "Instantiating mesh due to calling MeshFilter.mesh during edit mode. This will leak meshes. Please use MeshFilter.sharedMesh instead.". If I use sharedMesh, whenever I set the tilePosition for one, it changes for every tile too. Is there a safe way to deal with "instance UVs"? The system is meant to be quite simple, 1 quad per tile and 1 material w/ 1 big texture, I just go and tell which part of the texture I want to render in a specific tile.

Code is as simple as:

private void OnValidate()
{
    var uv = new Vector2[]
    {
        new Vector2(0, 0),
        new Vector2(1, 0),
        new Vector2(0, 1),
        new Vector2(1, 1),
    };

    var tex = GetComponent<MeshRenderer>().sharedMaterial.GetTexture("_MainTex");

    if (tex == null)
    {
        Debug.Log("no tex");
        return;
    }

    var texSize = new Vector2(tex.width, tex.height);
    var uvScale = tileSize / texSize;
    var uvOffset = tilePosition * tileSize / texSize;


    GetComponent<MeshFilter>().mesh.uv = uv
        .Select(v => (v + uvOffset / uvScale) * uvScale)
        .ToArray();
}
autumn crane
#

And yes, if you want separate uv data per tile, you'll end up with a quad mesh per tile, while originally each tile references the same mesh. So it's probably not the best approach if you plan to have a lot of tiles.

whole vessel
#

It seems like I can make a big texture for the chunk and SetPixels myself based on map texture, don't know the feasibility of that when it comes to performance so I'll keep researching

#

Apparently I can also (that one at 1st glance seems ideal) define different vertices for each tile and map their UVs separately

whole vessel
#

Turned out to be much simpler than I though lmaooo

#

Just had to add more vertices so I can map UVs to each tile

#

Found out after watching a 4 hours of a 12y old tutorial on youtube but worth it 😄