- Home /
How to create a Mesh made up of lines, not triangles
Is there any way to draw a Mesh without having triangles but lines (or points) instead? Do I really need to take the detour of a geometry shader? I am trying to draw a complex, constantly updating graph and I'm trying this the way I would if I had to solve this in OpenGL: by drawing a horizontal straight line with the number of vertices I need and then doing the vertical displacement in the vertex shader by looking up the y-axis from a 1D texture.
I already tried using a LineRenderer, but the result looks awful, as the thickness varies, depending on the steepness of the graph segment.
I tried creating a Mesh object in code, but realized they only expose methods/properties related to triangles.
As a workaround I'm currently drawing the line in OnRenderObject with GL.Vertex using a GL.LINE_STRIP (with seems a quite bad idea to me, but at least it does he job for the time being). Only issue is that now this graph for some reason now shows up in every camera, regardless of the culling mask I use.
So now I'm back to square one, seems to be a big deal in Unity. Is there a way of creating a Mesh object just made of lines? This would save me from quite some headache. Much appreciated!
Answer by Bunny83 · Mar 22, 2019 at 11:50 AM
Unity does support other mesh topologies for quite some time now. Just use Mesh.SetIndices instead of SetTriangles or triangles. See MeshTopology for more details.
Exactly what I was looking for, totally missed that, thanks!
Answer by juelzsantana123 · Apr 29, 2021 at 01:17 PM
using UnityEngine;
using System.Collections.Generic;
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
public class GridMesh : MonoBehaviour
{
public int xSize = 4;
public int ySize = 3;
[ColorUsage(true, true)]
public Color color = Color.red;
public Material material;
private void CreateGrid()
{
xSize = Mathf.Abs(xSize);
ySize = Mathf.Abs(ySize);
MeshFilter filter = gameObject.GetComponent<MeshFilter>();
var mesh = new Mesh();
var verticies = new List<Vector3>();
var indicies = new List<int>();
int indc = 0;
for (int i = 0; i <= xSize; i++)
{
verticies.Add(new Vector3(i, 0, 0));
verticies.Add(new Vector3(i, 0, ySize));
indicies.Add(indc++);
indicies.Add(indc++);
}
for (int j = 0; j <= ySize; j++)
{
verticies.Add(new Vector3(0, 0, j));
verticies.Add(new Vector3(xSize, 0, j));
indicies.Add(indc++);
indicies.Add(indc++);
}
mesh.vertices = verticies.ToArray();
mesh.SetIndices(indicies.ToArray(), MeshTopology.Lines, 0);
filter.mesh = mesh;
MeshRenderer meshRenderer = gameObject.GetComponent<MeshRenderer>();
meshRenderer.sharedMaterial = material;
meshRenderer.sharedMaterial.color = color;
}
private void OnValidate()
{
Mesh mesh = gameObject.GetComponent<MeshFilter>().sharedMesh;
if(mesh != null)
DestroyImmediate(mesh);
CreateGrid();
}
}
Your answer
