我编写了一个用于生成体素世界的脚本,其中在生成区域后,该脚本将 1 个块连接到 1 个网格。但这不会发生。该脚本没有将生成的体素分配给 Chunk 父级。为什么以及如何解决它?脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chunk : MonoBehaviour
{
public GameObject currentBlockType;
public int Seed;
public bool randomizeSeed;
public float smooth = 0;
public float multiplier = 0;
public int cols = 50;
public int rows = 50;
public bool CombineChunk;
private Vector3 myPos;
private Transform thisObject;
static private GameObject thisobjscr;
private void Start()
{
thisobjscr = gameObject;
thisObject = gameObject.transform;
if(randomizeSeed == true)
{
Seed = Random.Range(1, 200);
}
}
public void OnTriggerEnter(Collider other)
{
if(other.tag == "gen")
{
print("entered");
generate();
}
}
public void generate()
{
myPos = this.transform.position;
for (int x = 0; x < cols; x++)
{
for (int z = 0; z < rows; z++)
{
float y = Mathf.PerlinNoise((myPos.x + x) / smooth + Seed, (myPos.z + z) / smooth + Seed) * multiplier;
y = Mathf.Floor(y);
GameObject newBlock = GameObject.Instantiate(currentBlockType);
newBlock.transform.position = new Vector3(myPos.x + x, y, myPos.z + z );
if (CombineChunk == true)
{
newBlock.transform.SetParent(thisObject);
StartCoroutine(TimerForCombineWait());
}
}
}
}
IEnumerator TimerForCombineWait()
{
CombineChunk = false;
print("waiting for world stabilization: " + Time.time);
yield return new WaitForSeconds(1);
print("world stabilized in " + Time.time);
Combine();
}
public void Combine()
{
MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
int a = 0;
while (a < meshFilters.Length)
{
combine[a].mesh = meshFilters[a].sharedMesh;
combine[a].transform = meshFilters[a].transform.localToWorldMatrix;
meshFilters[a].gameObject.SetActive(false);
a++;
}
transform.GetComponent<MeshFilter>().mesh = new Mesh();
transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
transform.gameObject.SetActive(true);
gameObject.transform.position = new Vector3(0, 0, 0);
}
}
谢谢你。
我找到了一个解决方案,我只是将 combine 和 SetParent 函数向下移动。并且还添加了生成的状态,这样脚本在生成无限多的地形时不会死机。一切开始看起来像这样: