As The last ship sailed towards the distant horizon I sat there watching on a rock My mind slowly drifting away Forming into my... Dreamtale
Unity - Generate simple mesh from texture
2019-08-28 / 2 min read

Generate simple mesh from texture pixels

By creating a tight sprite with Unity API, then construct the mesh with this sprite's data.

Mesh SpriteToMesh(Sprite sprite)
{
    Mesh mesh = new Mesh();
    mesh.vertices = Array.ConvertAll(sprite.vertices, i => (Vector3) i);
    mesh.uv = sprite.uv;
    mesh.triangles = Array.ConvertAll(sprite.triangles, i => (int) i);

    return mesh;
}

private void OnGUI()
{
    if (GUI.Button(new Rect(10, 10, 100, 100), "hah"))
    {
        var tex = new Texture2D(mCanvasWidth, mCanvasHeight);
        var rect = new Rect(0, 0, mCanvasWidth, mCanvasHeight);
        RenderTexture.active = mRenderTexture1;
        
        // read pixels from rendertexture
        tex.ReadPixels(rect, 0, 0);
        tex.Apply();
        
        // create sprite from texture with SpriteMeshType.Tight
        var sprite = Sprite.Create(tex, rect, Vector2.one * 0.5f,
            100, 1, SpriteMeshType.Tight);

        //
        var mesh = SpriteToMesh(sprite);

        var go = new GameObject("hah", typeof(MeshRenderer), typeof(MeshFilter));
        go.transform.SetParent(this.transform);
        go.transform.localScale = Vector3.one;
        go.transform.localPosition = Vector3.zero;

        go.GetComponent<MeshFilter>().mesh = mesh;
        go.GetComponent<MeshRenderer>().material = CanvasMat;
    }
}