Created
August 27, 2022 15:05
-
-
Save PrashantUnity/f27763dcd3764e43249cc851ca801021 to your computer and use it in GitHub Desktop.
Mesh Generation basic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEditor; | |
[CustomEditor(typeof(MapGenerator))] | |
public class Edit : Editor | |
{ | |
public override void OnInspectorGUI() | |
{ | |
base.OnInspectorGUI(); | |
MapGenerator mapGenerator = (MapGenerator)target; | |
mapGenerator.Function(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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