Skip to content

Instantly share code, notes, and snippets.

@PrashantUnity
Created August 27, 2022 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PrashantUnity/f27763dcd3764e43249cc851ca801021 to your computer and use it in GitHub Desktop.
Save PrashantUnity/f27763dcd3764e43249cc851ca801021 to your computer and use it in GitHub Desktop.
Mesh Generation basic
using UnityEditor;
[CustomEditor(typeof(MapGenerator))]
public class Edit : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
MapGenerator mapGenerator = (MapGenerator)target;
mapGenerator.Function();
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class MapGenerator : MonoBehaviour
{
public List<Vector3> vertices;
public Vector2 size;
[Range(1, 100)]
public int resolution;
List<int> triangles;
Mesh mesh;
private void Start()
{
mesh = GetComponent<MeshFilter>().mesh;
GeneratePlane();
AssignMesh();
}
public void Function()
{
mesh = GetComponent<MeshFilter>().mesh;
GeneratePlane();
AssignMesh();
}
void GeneratePlane()
{
vertices = new List<Vector3>();
float xPerStep = size.x / resolution;
float yPerStep = size.y / resolution;
for (int y = 0; y < resolution + 1; y++)
{
for (int x = 0; x < resolution + 1; x++)
{
vertices.Add(new Vector3(x * xPerStep, 0, y * yPerStep));
}
}
triangles = new List<int>();
for (int row = 0; row < resolution; row++)
{
for (int column = 0; column < resolution; column++)
{
int i = (row * resolution) + column + row;
// first triangle
triangles.Add(i);
triangles.Add(i + resolution + 1);
triangles.Add(i + resolution + 2);
// second triangle
triangles.Add(i);
triangles.Add(i + resolution + 2);
triangles.Add(i + 1);
}
}
}
void AssignMesh()
{
mesh.Clear();
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment