Skip to content

Instantly share code, notes, and snippets.

@yoggy
Last active August 29, 2015 13:57
Show Gist options
  • Save yoggy/9778621 to your computer and use it in GitHub Desktop.
Save yoggy/9778621 to your computer and use it in GitHub Desktop.
save to "Assets/Editor" directory
using UnityEditor;
using UnityEngine;
using System.Collections;
public class CreateCylinderMesh : MonoBehaviour {
static int div_x = 40;
static int div_y = 20;
static float cylinder_width = 10.0f;
static float cylinder_height = 5.0f;
[MenuItem ("Create Object/CylinderMesh")]
static void Create ()
{
GameObject newGameobject = new GameObject ("CylinderMesh");
MeshRenderer meshRenderer = newGameobject.AddComponent<MeshRenderer> ();
meshRenderer.material = new Material (Shader.Find ("Diffuse"));
MeshFilter meshFilter = newGameobject.AddComponent<MeshFilter> ();
meshFilter.mesh = new Mesh ();
Mesh mesh = meshFilter.sharedMesh;
mesh.name = "CylinderMesh";
int w = div_x + 1;
int h = div_y + 1;
Vector3 [] vertices = new Vector3[w * h];
Vector2 [] uv = new Vector2[w * h];
int [] triangles = new int[div_x * div_y * 3 * 2];
int idx;
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
idx = x + y * w;
float px = x / (float)div_x;
float py = 1.0f - y / (float)div_y;
float r = cylinder_width / 2.0f;
float th = 2 * Mathf.PI * px;
float vx = r * -Mathf.Sin(th);
float vy = cylinder_height * py - cylinder_height / 2;
float vz = r * -Mathf.Cos(th);
vertices[idx] = new Vector3(vx, vy, vz);
float u = px;
float v = py;
uv[idx] = new Vector2(u, v);
}
}
idx = 0;
for (int y = 0; y < div_y; ++y)
{
for (int x = 0; x < div_x; ++x)
{
int base_idx = x + y * w;
triangles[idx ++] = base_idx;
triangles[idx ++] = base_idx + 1;
triangles[idx ++] = base_idx + w + 1;
triangles[idx ++] = base_idx + w + 1;
triangles[idx ++] = base_idx + w;
triangles[idx ++] = base_idx;
}
}
// まとめて設定するのがポイント
mesh.vertices = vertices;
mesh.uv = uv;
mesh.triangles = triangles;
mesh.RecalculateNormals ();
mesh.RecalculateBounds ();
mesh.Optimize ();
AssetDatabase.CreateAsset (mesh, "Assets/" + mesh.name + ".asset");
AssetDatabase.SaveAssets ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment