Unity网格生成:RowParent_0与RowParent_9无子物体原因咨询
问题分析:RowParent_0和RowParent_9无子女物体的原因
问题描述
使用Unity的GridGenerator脚本生成网格时,层级结构中的RowParent_0和RowParent_9没有子物体,运行无报错,咨询该现象是否符合逻辑及出现原因。
相关脚本代码
using UnityEngine; public class GridGenerator : MonoBehaviour { public GameObject gridCellPrefab; public int gridWidth = 10; public int gridHeight = 10; private GameObject[] wallParents = new GameObject[4]; private GameObject gridContainer; private GameObject[] rowParents; // Parents for each row of grid cells void Start() { CreateGridContainer(); GenerateGrid(); } void CreateGridContainer() { gridContainer = GameObject.Find("GridContainer"); if (gridContainer == null) { gridContainer = new GameObject("GridContainer"); gridContainer.transform.parent = this.transform; } // Initialize wall parent objects string[] wallNames = { "TopWallParent", "LeftWallParent", "RightWallParent", "BottomWallParent" }; for (int i = 0; i < wallParents.Length; i++) { wallParents[i] = new GameObject(wallNames[i]); wallParents[i].transform.parent = gridContainer.transform; } // Initialize row parent objects rowParents = new GameObject[gridHeight]; for (int i = 0; i < gridHeight; i++) { rowParents[i] = new GameObject("RowParent_" + i); rowParents[i].transform.parent = gridContainer.transform; } } public void GenerateGrid() { // Clear previous grid foreach (Transform child in gridContainer.transform) { Destroy(child.gameObject); } CreateGridContainer(); // Recreate wall and row parents // Generate new grid for (int x = 0; x < gridWidth; x++) { for (int z = 0; z < gridHeight; z++) { GameObject cell = Instantiate(gridCellPrefab, new Vector3(x * 1.5f, 0, z * 1.5f), Quaternion.identity); cell.name = "GridCell_" + x + "_" + z; cell.tag = "GridCell"; cell.GetComponent<Renderer>().material.color = new Color(0.945f, 1f, 0f); // Adjust parent based on position if (x == 0) { cell.transform.parent = wallParents[0].transform; cell.name = "TopWallCell_" + z; } else if (z == 0) { cell.transform.parent = wallParents[1].transform; cell.name = "LeftWallCell_" + x; } else if (z == gridHeight - 1) { cell.transform.parent = wallParents[2].transform; cell.name = "RightWallCell_" + x; } else if (x == gridWidth - 1) { cell.transform.parent = wallParents[3].transform; cell.name = "BottomWallCell_" + z; } else { cell.transform.parent = rowParents[z].transform; } } } } }
原因分析
这个现象完全符合代码逻辑,核心原因在于单元格父物体的条件判断顺序和规则:
- 当
z=0(对应RowParent_0)时,只要x≠0(x=0的情况已被第一个x==0条件归类到TopWallParent),就会触发z==0的判断,将单元格放到LeftWallParent,永远不会走到最后的else分支(不会赋值给RowParent_0)。 - 当
z=gridHeight-1(即z=9,对应RowParent_9)时,只要x≠0,就会触发z==gridHeight-1的判断,将单元格放到RightWallParent,同样不会走到else分支。 - 只有当单元格同时满足
x≠0、x≠gridWidth-1、z≠0、z≠gridHeight-1时,才会被赋值给对应的RowParent[z]。
结论
该现象是代码设计的正常结果,并非错误。RowParent_0和RowParent_9会被创建,但永远不会有子物体,因为它们对应的z轴行的所有单元格都被归类到墙的父物体中了。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

