Last active
August 29, 2015 14:01
-
-
Save MasashiWada/19853c3d567a27dcea51 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using System.Collections; | |
| public class SkinmeshInstancing : MonoBehaviour | |
| { | |
| // 表示したいメッシュのプレハブを設定してね (※ボーンアニメーション付きのものは未対応) | |
| public GameObject prefabBase; | |
| // 同時に表示したい数 | |
| public int InstanceNum = 10; | |
| // 個別のメッシュを操作するTransform | |
| private Transform[] boneTransform; | |
| void Awake() | |
| { | |
| var meshrd = prefabBase.GetComponent<MeshFilter>(); | |
| var mesh = createskinmesh(meshrd.sharedMesh, InstanceNum); | |
| boneTransform = new Transform[InstanceNum]; | |
| for (int i = 0; i < InstanceNum; i++) | |
| boneTransform[i] = new GameObject(this.name + "_bone_" + i).transform; | |
| var smr = gameObject.AddComponent<SkinnedMeshRenderer>(); | |
| smr.sharedMesh = mesh; | |
| smr.sharedMaterial = prefabBase.renderer.sharedMaterial; | |
| smr.rootBone = this.transform; | |
| smr.bones = boneTransform; | |
| // シーンに xxxxx_bone_N の名前のGameObjectがInstanceNum個出現するので、それらを移動させたり回転させたり | |
| } | |
| private Mesh createskinmesh(Mesh baseMesh, int num) | |
| { | |
| var mesh = new Mesh(); | |
| mesh.name = this.name; | |
| var combine = new CombineInstance[num]; | |
| for (int i = 0; i < num; i++) | |
| { | |
| combine[i].mesh = baseMesh; | |
| combine[i].transform = Matrix4x4.identity; | |
| } | |
| mesh.CombineMeshes(combine); | |
| var bindPoses = new Matrix4x4[num]; | |
| var weights = new BoneWeight[mesh.vertexCount]; | |
| int basevertics = baseMesh.vertexCount; | |
| for (int i = 0; i < num; i++) | |
| { | |
| for (int x = 0; x < basevertics; x++) | |
| { | |
| weights[i * basevertics + x].boneIndex0 = i; | |
| weights[i * basevertics + x].weight0 = 1; | |
| } | |
| bindPoses[i] = Matrix4x4.identity; | |
| } | |
| mesh.boneWeights = weights; | |
| mesh.bindposes = bindPoses; | |
| return mesh; | |
| } | |
| void Start() | |
| { | |
| // 表示する対象をランダムに散らばす | |
| for (int i = 0; i < boneTransform.Length; i++) | |
| { | |
| boneTransform[i].position = new Vector3(Random.Range(-3.0f, 3.0f), Random.Range(-3.0f, 3.0f), Random.Range(-3.0f, 3.0f)); | |
| boneTransform[i].rotation = Quaternion.Euler(Random.Range(-180.0f, 180.0f), Random.Range(-180.0f, 180.0f), Random.Range(-180.0f, 180.0f)); | |
| var scl = Random.Range(0.5f, 2.0f); | |
| boneTransform[i].localScale = new Vector3(scl, scl, scl); | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment