どういう記事?
ターゲット:既成のFBXを使わず、スクリプトからMeshをいろいろ変更したい人
内容:Meshの要素の変更をMeshFilterに反映する簡潔(だと思う)なコード
public class Model
{
private Material myMaterial;
private Mesh myMesh;
private Bounds myBounds;
public Model(GameObject gameObject)
{
myBounds = new Bounds();
myMesh = new Mesh();
myMaterial = new Material();
gameObject.GetComponent<MeshFilter>().mesh = myMesh;
gameObject.GetComponent<Renderer>().material = myMaterial;
}
public void SetVertsAndIndices()
{
Vector3[] vertices = 頂点;
int[] indices = インデックス配列;
myMesh.vertices = vertices;
myMesh.subMeshCount = 1;
myMesh.SetIndices(indices, MeshTopology.なにか, 0);
}
public void OnMaterialChange()
{
myMaterial.SetBuffer("なんかのデータ", buffer_なんかのデータ);
}
public void CalculateBounds()
{
myBounds.SetMinMax(min, max);
myMesh.bounds = myBounds;
}
}
Meshについて
meshfilter.mesh
で取得できるMeshはmeshfilterで使われるものコピーなので、コピーへの操作はmeshfilterに反映されない
meshfilter.mesh.vertices = newVertices; // meshfilterには反映されない
変更したいメッシュをメンバ変数として持ちながら、meshfilter.mesh
に代入することで、メンバ変数への操作をmeshfilterに影響させることができる
myMesh = new Mesh(); // = meshfilter.meshで現在のコピーをメンバ変数にすることもできる
meshfilter.mesh = myMesh;
//myMeshに変更を加えたい時
myMesh.vertices = newVertices; // meshfilterに反映される
Boundsについて
boundsは mesh.bounds = newBounds
とする以外にmeshとmeshfilterに影響することができない(と思う)
myMesh.bounds.SetMinMax(min,max); //myMeshには変更が届かない
myBounds = new Bounds();
myMesh.bounds = myBounds; //この時のmyBoundsの値は設定されるけど…?
//Boundsの大きさが変わった時
myBounds.SetMinMax(min,max); //meshには変更が届かない
myBounds = new Bounds();
//Boundsの大きさが変わった時
myBounds.SetMinMax(min,max);
myMesh.bounds = myBounds; //myMeshのboundsが変更されるよ