Skip to content

Instantly share code, notes, and snippets.

@openroomxyz
Created April 21, 2020 12:24
Show Gist options
  • Save openroomxyz/193218a2c4b4520703b99a975386ecdf to your computer and use it in GitHub Desktop.
Save openroomxyz/193218a2c4b4520703b99a975386ecdf to your computer and use it in GitHub Desktop.
Unity : How can i procedural generate geometry, create object, attach material to it? (example)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateQuard : MonoBehaviour
{
public Material material;
// Start is called before the first frame update
void Start()
{
Create();
}
void Create()
{
Mesh mesh = new Mesh();
mesh.name = "Name of created new Mesh";
Vector3[] vertices = new Vector3[4];
Vector3[] normals = new Vector3[4];
Vector2[] uvs = new Vector2[4];
int[] trinagles = new int[6];
//all posibile UVs
Vector2 uv00 = new Vector2(0f, 0f);
Vector2 uv01 = new Vector2(0f, 1f);
Vector2 uv10 = new Vector2(1f, 0f);
Vector2 uv11 = new Vector2(1f, 1f);
//all posibile vertices (of the cube!)
Vector3 p0 = new Vector3(-0.5f, -0.5f, 0.5f);
Vector3 p1 = new Vector3( 0.5f, -0.5f, 0.5f);
Vector3 p2 = new Vector3( 0.5f, -0.5f, -0.5f);
Vector3 p3 = new Vector3(-0.5f, -0.5f, -0.5f);
Vector3 p4 = new Vector3(-0.5f, 0.5f, 0.5f);
Vector3 p5 = new Vector3( 0.5f, 0.5f, 0.5f);
Vector3 p6 = new Vector3( 0.5f, 0.5f, -0.5f);
Vector3 p7 = new Vector3(-0.5f, 0.5f, -0.5f);
vertices = new Vector3[] { p4, p5, p1, p0 };
normals = new Vector3[] { Vector3.forward, Vector3.forward, Vector3.forward, Vector3.forward };
uvs = new Vector2[] { uv11, uv01, uv00, uv10 };
trinagles = new int[] { 3, 1, 0, 3, 2, 1 };
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uvs;
mesh.triangles = trinagles;
//Calculate the bounding box that encompasses the mesh,
//it's used for rendering if you has wrong bounding box
//it may or not get ocluded or not when it needs to be
//so it's a good idea to always do this when you are playing with meshes
mesh.RecalculateBounds();
GameObject quard = new GameObject("quard");
quard.transform.parent = this.gameObject.transform;
MeshFilter meshFilter = (MeshFilter)quard.AddComponent(typeof(MeshFilter));
meshFilter.mesh = mesh;
MeshRenderer renderer = quard.AddComponent(typeof(MeshRenderer)) as MeshRenderer;
renderer.material = material;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment