- Home /
Failed creating polygon mesh from script
I am trying to create a new gameobject with polygon mesh from a set of points.
pointList is a list of points in clockwise order.
My script doesn't work and I couldn't tell why. Could anyone tell me what's wrong?
Many thanks!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CreateSurface : MonoBehaviour
{
public GameObject surfaceVisualizer;
private int[] meshIndices;
private Vector3[] pointLocation;
private GameObject surface;
public void Start()
{
surface = new GameObject("New Surface");
surface.AddComponent<MeshRenderer>();
surface.AddComponent<MeshFilter>();
}
public GameObject creatSurface(List<GameObject> pointList, string meshName)
{
surface.name = meshName;
surface.GetComponent<MeshRenderer>().material = surfaceVisualizer.GetComponent<MeshRenderer>().material;
// Generate Mesh.
Mesh mesh = surface.GetComponent<MeshFilter>().mesh;
mesh.name = meshName;
mesh.Clear();
int pointCount = pointList.Count;
for (int i = 0; i < pointCount; i++)
{
pointLocation[i] = pointList[i].transform.position;
}
for (int i = 0; i < pointCount - 1; i++)
{
meshIndices[3 * i] = i;
meshIndices[3 * i + 1] = i + 1;
meshIndices[3 * i + 2] = pointCount - i - 1;
}
mesh.vertices = pointLocation;
mesh.triangles = meshIndices;
mesh.Optimize();
mesh.RecalculateNormals();
return Instantiate(surface, pointList[0].transform.position, pointList[0].transform.rotation);
}
}
Answer by Bunny83 · Nov 04, 2019 at 11:51 AM
Well your triangle list doesn't really seem to make much sense. Also note that you can not simply create a polygon. Unity only supports the topologies: Triangles or Quads for "filled" geometry. So if you have a point loop you have to triangulate it yourself. Note that if your points form a convex polygon it is quite trivial since you can simply create a triangle fan around one point (usually the first one). If that is the case all you need to do is this:
for (int i = 0; i < pointCount - 2; i++)
{
meshIndices[3 * i] = 0;
meshIndices[3 * i + 1] = i + 1;
meshIndices[3 * i + 2] = i + 2;
}
However if your points do not resemble a convex polygon this will not work in many cases. Now you need to actually triangulate the polygon. Note that polygons are 2 dimensional shapes. If you have different heights (the points do not lie in the same plane) it's not really a polygon and there might be several ways how to create a surface between the points. There is the Triangulator script on the wiki which can triangulate a 2d polygon.
Your answer
Follow this Question
Related Questions
TextMesh/3DText modify shape 0 Answers
How to create a mesh with coordinates given from an Arduino? 1 Answer
Drawing new mesh not working 1 Answer
Runtime mesh decimation 1 Answer
Export game objects with mesh paths 0 Answers