Skip to content

Instantly share code, notes, and snippets.

@todorok1
Created January 20, 2021 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todorok1/4084273813b29fdd80364645b200fc9e to your computer and use it in GitHub Desktop.
Save todorok1/4084273813b29fdd80364645b200fc9e to your computer and use it in GitHub Desktop.
エディタ上でパーリンノイズによる地形を生成するサンプル
/// <Summary>
/// フィールドのパーツを結合するメソッドです。
/// </Summary>
void CombineFieldParts(FieldGenerator generator)
{
// 地形オブジェクトのMeshFilterへの参照を配列として保持します。
MeshFilter[] meshFilters = generator.fieldParent.GetComponentsInChildren<MeshFilter>();
MeshRenderer[] meshRenderers = generator.fieldParent.GetComponentsInChildren<MeshRenderer>();
// MeshFilterとMeshRendererの数が合っていない場合は処理を抜けます。
if (meshFilters.Length != meshRenderers.Length)
{
return;
}
// 結合したオブジェクトを格納するオブジェクトを作成します。
GameObject combineParent = new GameObject();
combineParent.name = "CombineParent";
combineParent.transform.position = Vector3.zero;
// 結合済みのオブジェクトを格納するオブジェクトを作成します。
GameObject combinedObjects = new GameObject();
// 子オブジェクトのメッシュをマテリアルごとにグループ分けします。
Dictionary<string, Material> matNameDict = new Dictionary<string, Material>();
Dictionary<string, List<MeshFilter>> matFilterDict = new Dictionary<string, List<MeshFilter>>();
for (int i = 0; i < meshFilters.Length; i++)
{
Material mat = meshRenderers[i].sharedMaterial;
string matName = mat.name;
// 辞書のキーにマテリアルが登録されていない場合はMeshFilterのリストを追加します。
if (!matFilterDict.ContainsKey(matName))
{
List<MeshFilter> filterList = new List<MeshFilter>();
matFilterDict.Add(matName, filterList);
matNameDict.Add(matName, mat);
}
matFilterDict[matName].Add(meshFilters[i]);
}
// グループ分けしたマテリアルごとにオブジェクトを作成し、メッシュを結合します。
foreach (KeyValuePair<string, List<MeshFilter>> pair in matFilterDict)
{
// 結合したメッシュを表示するゲームオブジェクトを作成します。
GameObject obj = CreateMeshObj(pair.Key, combineParent);
obj.transform.SetAsFirstSibling();
// MeshFilterとMeshRendererをアタッチします。
MeshFilter combinedMeshFilter = CheckComponent<MeshFilter>(obj);
MeshRenderer combinedMeshRenderer = CheckComponent<MeshRenderer>(obj);
// 結合するメッシュの配列を作成します。
List<MeshFilter> filterList = pair.Value;
CombineInstance[] combine = new CombineInstance[filterList.Count];
// 結合するメッシュの情報をCombineInstanceに追加していきます。
for (int i = 0; i < filterList.Count; i++)
{
combine[i].mesh = filterList[i].sharedMesh;
combine[i].transform = filterList[i].transform.localToWorldMatrix;
filterList[i].gameObject.transform.SetParent(combinedObjects.transform);
filterList[i].gameObject.SetActive(false);
// 進捗を表示します。
if (i % 10 == 0)
{
float progress = (float) (i + 1) / filterList.Count;
EditorUtility.DisplayProgressBar(
"メッシュの結合中(" + pair.Key + ")",
i.ToString() + "項目(" + (progress * 100).ToString("F2") + "%)",
progress
);
}
}
EditorUtility.ClearProgressBar();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment