3D无尽跑酷游戏:Z轴间隔生成X轴随机路径块方案咨询
解决方案
完全可以通过随机生成单个方块替代预制体组合,既省去手动制作31种组合的麻烦,又能大幅降低内存占用。核心思路是预先定义X轴上的5个方块位置,在每个Z轴间隔点随机选择1-4个位置生成方块,同时确保至少保留一个方块作为前进路径。
修改后的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GenerateLevel : MonoBehaviour { // 单个方块预制体(替代原组合预制体数组) public GameObject squarePrefab; public int zPos = 50; public bool creatingSection = false; // X轴上的5个方块位置(可根据你的方块尺寸调整数值) private float[] xPositions = new float[] { -2f, -1f, 0f, 1f, 2f }; void Update() { if (!creatingSection) { creatingSection = true; StartCoroutine(GenerateSection()); } } IEnumerator GenerateSection() { // 随机确定本次生成1-4个方块 int squareCount = Random.Range(1, 5); // 存储已选X位置索引,避免重复生成 HashSet<int> selectedIndices = new HashSet<int>(); // 随机挑选不重复的位置索引 while (selectedIndices.Count < squareCount) { int randomIndex = Random.Range(0, xPositions.Length); selectedIndices.Add(randomIndex); } // 在选中的位置生成方块 foreach (int index in selectedIndices) { float x = xPositions[index]; Instantiate(squarePrefab, new Vector3(x, 0, zPos), Quaternion.identity); } zPos += 50; yield return new WaitForSeconds(2); creatingSection = false; } }
逻辑说明
- 预制体简化:仅需单个方块预制体,彻底消除31种组合预制体的资源冗余。
- X轴位置配置:
xPositions数组对应5个方块的X坐标,可根据实际方块尺寸、布局需求调整数值(比如方块宽度为2单位时,可改为-4f, -2f, 0f, 2f, 4f)。 - 随机生成控制:
- 随机确定本次生成1-4个方块,避免全空或全满的情况
- 用
HashSet确保选中的X位置不重复,防止同一位置生成多个方块 - 遍历选中位置逐个生成方块,完成当前Z段的布局
- 路径保障:生成数量固定为1-4个,不会出现无方块的情况,玩家始终有前进落脚点。
额外优化建议
若后期方块数量过多导致内存压力,可引入对象池机制:
- 预先创建一批方块存入对象池
- 需要生成时从池内取出闲置方块,设置位置后激活
- 玩家远离后将方块回收到池内,而非直接销毁,减少频繁实例化/销毁的性能消耗
内容的提问来源于stack exchange,提问作者Pete
相关产品推荐
相关产品推荐

