Search code examples
unity-game-enginecanvas

Display custom mesh on Canvas


Hey i want to draw some custom meshes on a Canvas object in my scene. The Canvas uses Render Mode World Space. I wrote a simple script creating a rectangle mesh based on the Canvas dimensions. It works when using a MeshFilter and MeshRenderer but i want to draw it directly onto the canvas. I tried using CanvasRenderer.SetMesh() but nothing appears.

using UnityEngine;

public class MeshCanvas : MonoBehaviour
{
    Vector3[] vertices;
    int[] triangles;
    Mesh mesh;

    float canvasHeigt;
    float canvasWidth;

    public float offset = 10f;

    private void Update()
    {
        canvasHeigt = FindObjectOfType<Canvas>().GetComponent<RectTransform>().rect.height;
        canvasWidth = FindObjectOfType<Canvas>().GetComponent<RectTransform>().rect.width;

        vertices = new Vector3[]
        {
            new Vector3(0 + offset, 0 + offset),
            new Vector3(0 + offset, canvasHeigt - offset),
            new Vector3(canvasWidth - offset, canvasHeigt - offset),
            new Vector3(canvasWidth - offset, 0 + offset)
        };

        triangles = new int[]
        {
            0, 1, 2,
            2, 3, 0
        };

        mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        this.GetComponent<MeshFilter>().mesh = mesh;
    }
}

Solution

  • You need to set a material on the CanvasRenderer to see your mesh.

    // this.GetComponent<MeshFilter>().mesh = mesh; // not necessary
    
    Material material = ...  // get your mat
    
    CanvasRenderer cr = GetComponent<CanvasRenderer>();
    cr.materialCount = 1;
    cr.SetMaterial(material, 0);
    cr.SetMesh(mesh);