You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity生成10x10x10立方体位置JSON数据重复问题排查

问题根源

  • 外层多余的x循环导致每个立方体坐标被重复覆盖1000次,所有元素最终都保留了最后一次循环的最大值坐标
  • cubeDatas数组未初始化,直接访问会触发空引用异常
  • 仅给depth设置了默认值10,rows和columns默认值为0,未手动配置的情况下循环不会执行
  • 没有建立三层循环坐标和数组下标的对应关系

修复后完整代码

using UnityEngine;
using System.IO;
using System.Collections.Generic;

public class JSONWriter : MonoBehaviour
{
    [SerializeField] int rows = 10, columns = 10, depth = 10;
    [SerializeField] float padding = 1f;

    public enum CubeType
    {
        white,
        yellow,
        blue,
        red,
        green
    }

    private readonly IReadOnlyDictionary<CubeType, Color> colors = new Dictionary<CubeType, Color>
    {
        {CubeType.white, Color.white},
        {CubeType.yellow, Color.yellow},
        {CubeType.blue, Color.blue},
        {CubeType.red, Color.red},
        {CubeType.green, Color.green}
    };

    [System.Serializable]
    public class CubeData
    {
        public Vector3 cubePosition;
        public CubeType Cube;
    }
    
    [System.Serializable]
    public class CubeDataList
    {
        public CubeData[] cubeDatas;
    }

    [ContextMenu("导出JSON")]
    public void outputJSON()
    {
        // 自动创建Resources文件夹避免写入报错
        string dirPath = Application.dataPath + "/Resources";
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }
        string strOutput = JsonUtility.ToJson(myCubeDataList, prettyPrint:true);
        File.WriteAllText(dirPath + "/10x10x10.txt", strOutput);
        Debug.Log("JSON导出完成,路径:" + dirPath + "/10x10x10.txt");
    }

    public CubeDataList myCubeDataList = new CubeDataList();

    void Start()
    {
        // 初始化数组
        int totalCount = depth * columns * rows;
        myCubeDataList.cubeDatas = new CubeData[totalCount];

        // 直接用三层循环生成坐标,每个坐标只赋值一次
        for (int i = 0; i < depth; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                for (int k = 0; k < rows; k++)
                {
                    // 计算对应数组下标
                    int index = i * columns * rows + j * rows + k;
                    // 初始化CubeData实例
                    myCubeDataList.cubeDatas[index] = new CubeData();
                    // 赋值坐标
                    myCubeDataList.cubeDatas[index].cubePosition = new Vector3(i, j, k) * padding;
                    // 随机赋值立方体类型,已修复原错误写法
                    myCubeDataList.cubeDatas[index].Cube = (CubeType)Random.Range(0, System.Enum.GetValues(typeof(CubeType)).Length);
                }
            }
        }
    }
}

验证说明

运行后在Inspector面板右键该脚本组件,点击「导出JSON」即可得到坐标不重复的1000条立方体数据,padding参数可直接在Inspector调整,行/列/深度参数也可按需修改。

内容的提问来源于stack exchange,提问作者IcyThug

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 16:15:04