Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- [ExecuteInEditMode]
- public class ProceduralCylinder : MonoBehaviour
- {
- public Mesh m_CylinderMesh = null;
- public Material m_Material = null;
- public int m_RadiusSubdivisions = 10;
- public int m_HeightSubdivisions = 5;
- public float m_Radius = 1.0f;
- public float m_Height = 5.0f;
- private Vector3[] m_Vertices;
- private Vector2[] m_UVs;
- private int[] m_Triangles;
- [ContextMenu("Generate Mesh")]
- public void GenerateMesh()
- {
- if(m_CylinderMesh != null)
- {
- if(Application.isPlaying)
- {
- Destroy(m_CylinderMesh);
- }
- else
- {
- DestroyImmediate(m_CylinderMesh);
- }
- }
- m_CylinderMesh = new Mesh();
- m_CylinderMesh.name = "Cylinder_" + gameObject.name;
- m_Vertices = new Vector3[(m_HeightSubdivisions + 1) * m_RadiusSubdivisions];
- m_UVs = new Vector2[m_Vertices.Length];
- m_Triangles = new int[6 * m_HeightSubdivisions * m_RadiusSubdivisions];
- int currentTriangle = 0;
- for(int i = 0; i < m_HeightSubdivisions + 1; i++)
- {
- float yUV = ((float)i / (float)m_HeightSubdivisions);
- float height = yUV * m_Height;
- for(int j = 0; j < m_RadiusSubdivisions; j++)
- {
- float xUV = ((float)j / (float)m_RadiusSubdivisions);
- float rad = xUV * Mathf.PI * 2.0f;
- Vector3 pos = new Vector3(Mathf.Cos(rad) * m_Radius, height, Mathf.Sin(rad) * m_Radius);
- int idx0 = (i * m_RadiusSubdivisions + j);
- m_Vertices[idx0] = pos;
- m_UVs[idx0] = new Vector2(xUV, yUV);
- if(i < m_HeightSubdivisions)
- {
- int idx1 = ((i + 1) * m_RadiusSubdivisions + j);
- int idx2 = ((i + 1) * m_RadiusSubdivisions + ((j + 1) % m_RadiusSubdivisions));
- int idx3 = (i * m_RadiusSubdivisions + ((j + 1) % m_RadiusSubdivisions));
- m_Triangles[currentTriangle + 0] = idx0;
- m_Triangles[currentTriangle + 1] = idx1;
- m_Triangles[currentTriangle + 2] = idx2;
- m_Triangles[currentTriangle + 3] = idx0;
- m_Triangles[currentTriangle + 4] = idx2;
- m_Triangles[currentTriangle + 5] = idx3;
- currentTriangle += 6;
- }
- }
- }
- m_CylinderMesh.vertices = m_Vertices;
- m_CylinderMesh.uv = m_UVs;
- m_CylinderMesh.triangles = m_Triangles;
- m_CylinderMesh.RecalculateBounds();
- m_CylinderMesh.RecalculateNormals();
- m_CylinderMesh.RecalculateTangents();
- }
- private void Update()
- {
- Camera camera = Camera.main;
- if(m_CylinderMesh != null)
- {
- Graphics.DrawMesh(m_CylinderMesh, transform.localToWorldMatrix, m_Material, gameObject.layer);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement