Drawing simple shapes on Canvas,How to draw simple shapes on Canvas
As I'm making a UI, I find myself in need to create some non standard shapes on the Canvas. I do not know exactly where these shapes are going to be placed, or the exact shape itself, before runtime (so they need to be implemented through script), but they are not going to be any more complicated than triangles or trapezoids. They also need to be filled in, so something like Line Renderer is not going to be of use. I have spent a good day googling this, but it doesn't seem as easy as it ought to be for an issue I'm sure a lot of people have come across. Does anyone know how I should go about doing this?
Suggestions for premade assets which can make my life easier is also welcome, but a solution without it is preferable (It's a hassle to buy assets through the company I currently work at, but it is possible),
Answer by AndyLangberg · Sep 03, 2018 at 10:29 AM
To answer my own question:
private Vector3[] newVertices;
[SerializeField]
private Material material;
// Tringle order for this spesific rectangle for all faces to face towards camera.
private int[] newTriangles = new int[] { 0, 1, 2, 0, 2, 3 };
public void Start()
{
Mesh mesh = new Mesh();
Vector3 V1 = new Vector3(0, 0, 0);
Vector3 V2 = new Vector3(0, 100, 0);
Vector3 V3 = new Vector3(100, 100, 0);
Vector3 V4 = new Vector3(100, 0, 0);
newVertices = new Vector3[] { V1, V2, V3, V4 };
mesh.vertices = newVertices;
mesh.triangles = newTriangles;
CanvasRenderer rend = GetComponent<CanvasRenderer>();
rend.SetMaterial(material, null);
rend.SetMesh(mesh);
}
This creates a rectangle or trapezoid. Making a triangle is as easy as just putting two of the Vectors on the same place. Triangle order might need to be adjusted depending on the position of the vectors (Meshes will only be drawn facing one side, and it is the side where the triangle is drawn clockwise)
Material is required, or it will just silently fail.
Answer by tormentoarmagedoom · Aug 29, 2018 at 06:15 PM
Good day.
If you know how they will be, you only need to create some sprites with some editor (maybe just by grupping triangles) I can be any sorm, maybe then you need to check the line renderer component.
Bye!
I did specify that I do not know how they are going to be.
The line renderer does not fill in the shapes. I'm updating the question to add that point, as that is important. I also don't think line renderer can be drawn on a canvas? But I could be mistaken about that.