Skip to content

Instantly share code, notes, and snippets.

@BigETI
Created August 27, 2020 18:56
Show Gist options
  • Save BigETI/8c1b3c74f8fa18f5100174f43f05e079 to your computer and use it in GitHub Desktop.
Save BigETI/8c1b3c74f8fa18f5100174f43f05e079 to your computer and use it in GitHub Desktop.
An class that allows generating plane meshes.
using System;
using System.Threading.Tasks;
using UnityEngine;
/// <summary>
/// Plane class
/// </summary>
public static class Plane
{
/// <summary>
/// Create plane mesh
/// </summary>
/// <param name="resolution">Resolution</param>
/// <param name="size">Size</param>
/// <param name="pivot">Pivot</param>
/// <returns>Plane mesh</returns>
public static Mesh CreatePlaneMesh(Vector2Int resolution, Vector2 size, Vector3 pivot)
{
if ((resolution.x < 1) || (resolution.y < 1))
{
throw new ArgumentException($"Invalid resolution { resolution }. Resolution should be atleast { Vector2Int.one }.", nameof(resolution));
}
Mesh ret = new Mesh();
Vector3[] vertices = new Vector3[(resolution.x + 1) * (resolution.y + 1)];
int[] indices = new int[resolution.x * resolution.y * 6];
Vector3[] normals = new Vector3[vertices.Length];
Vector2[] uvs = new Vector2[vertices.Length];
Parallel.For(0, vertices.Length, (index) =>
{
Vector2Int id = new Vector2Int(index % (resolution.x + 1), index / (resolution.x + 1));
vertices[index] = new Vector3(((size.x * id.x) / resolution.x) - pivot.x, ((size.y * id.y) / resolution.y) - pivot.y, -pivot.z);
normals[index] = Vector3.back;
if ((id.x < resolution.x) && (id.y < resolution.y))
{
int offset = (id.x * 6) + ((id.y * resolution.x * 6));
indices[offset] = index;
indices[offset + 1] = index + resolution.x + 1;
indices[offset + 2] = index + 1;
indices[offset + 3] = index + 1;
indices[offset + 4] = index + resolution.x + 1;
indices[offset + 5] = index + resolution.x + 2;
}
uvs[index] = id;
});
ret.vertices = vertices;
ret.SetIndices(indices, MeshTopology.Triangles, 0);
ret.normals = normals;
ret.SetUVs(0, uvs);
ret.UploadMeshData(true);
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment