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

Unity中向GameObject二维数组赋值返回null问题求助

问题分析与解决:GameObject二维数组赋值后显示null

核心问题原因

你遇到的null输出并不是数组赋值失败,而是调试时访问了错误的数组索引:
在赋值语句中使用了yCounter++,这会先以当前yCounter的值完成数组元素赋值,随后立刻将yCounter加1。紧接着的Debug.Log访问的是已经递增后的yCounter索引,而这个位置还未被赋值,因此输出null。实际上你已经成功将实例化的GameObject存入了数组的正确位置。

修正后的代码

void PlaceBricks(){
    placedBricksPositions=new GameObject[columnNumber*2,rowNumber*2]; // 预留足够空间
    FixBorders();
    List<GameObject> bricksWithRates=GetBrickWithRatesList();

    int xCounter=0;

    for(float x=topRight.x;x>=bottomLeft.x;x-=(topRight.x-bottomLeft.x)/columnNumber){
        int yCounter=0;
        Debug.Log("hola");
        for(float y=topRight.y;y>=bottomLeft.y;y-=(topRight.y-bottomLeft.y)/rowNumber){
            // 先实例化并赋值到正确索引
            GameObject newBrick = Instantiate(
                GetBrickToSpawn(bricksWithRates),new Vector3(x,y,0),Quaternion.identity);
            placedBricksPositions[xCounter, yCounter] = newBrick;
            
            // 调试时访问刚赋值的索引
            Debug.Log(placedBricksPositions[xCounter, yCounter]);
            // 手动递增索引
            yCounter++;
        }
        xCounter++;
    }
}

额外说明

  • 你也可以将yCounter的递增放到for循环的增量部分,逻辑会更清晰:
    for(int yCounter=0; y <= rowNumber*2; yCounter++){
        // 循环逻辑
    }
    
  • 若要验证数组是否真的赋值成功,可以在两层循环结束后,遍历数组的有效索引范围,查看对应的元素值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:52:36