Unity使用脚本生成立方体模型
unity版本2019.4.0f1
文件一览
记得给物体赋予材质!
CubeMesh.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeMesh : MonoBehaviour
{
MeshRenderer meshRenderer;
MeshFilter meshFilter;
MeshCollider meshCollider;
//存放顶点数据
List<Vector3> verts;
List<int> indices;
// Start is called before the first frame update
private void Start()
{
verts=new List<Vector3>();
indices=new List<int>();
meshRenderer=GetComponent<MeshRenderer>();
meshFilter=GetComponent<MeshFilter>();
meshCollider=GetComponent<MeshCollider>();
Generate();
}
public void Generate(){
ClearMeshData();
//填写数据
AddMeshData();
//传递数据给Mesh,生成真正网格
Mesh mesh=new Mesh();
mesh.vertices=verts.ToArray();
mesh.triangles=indices.ToArray();
//自动计算法线
mesh.RecalculateNormals();
//自动计算物体整体边界
mesh.RecalculateBounds();
meshFilter.mesh=mesh;
//碰撞体专用mesh,只负责物体碰撞外形
meshCollider.sharedMesh=mesh;
}
void ClearMeshData(){
verts.Clear();
indices.Clear();
}
void AddMeshData(){
verts.Add(new Vector3(0,0,0));
verts.Add(new Vector3(0,0,1));
verts.Add(new Vector3(1,0,1));
verts.Add(new Vector3(1,0,0));
verts.Add(new Vector3(0,1,1));
verts.Add(new Vector3(0,1,0));
verts.Add(new Vector3(1,1,1));
verts.Add(new Vector3(1,1,0));
//绘制第一个三角面片(顺时针)
indices.Add(0);
indices.Add(1);
indices.Add(2);//end first
indices.Add(0);
indices.Add(2);
indices.Add(3);//end second
indices.Add(0);
indices.Add(5);
indices.Add(4);//end third
}
// Update is called once per frame
void Update()
{
}
}
效果图:
解释一下,多个面片可以围成一个立方体,没绘制完三角面片😅
参考资料:
[1]https://www.bilibili.com/video/BV1FD4y1Q7uA/
[2]https://www.bilibili.com/video/BV1Dv411B76b/