Unity-实例化游戏对象后错误放置它们

时间:2019-05-07 14:13:43

标签: c# unity3d gameobject

我使用以下代码实例化一个棋盘游戏对象:

mainBoard.transform.position = camera.ViewportToWorldPoint(new Vector3(0f, 0f, camera.nearClipPlane));

然后我尝试通过使用循环实例化Tiles GameObjects来填充此面板:

for (int x = 0; x < width; x++)
         {
             for (int y = 0; y < height; y++)
             {                
                 Vector3 tempPosition = camera.ViewportToWorldPoint(new Vector3(x, y, camera.nearClipPlane));                    
                 GameObject backgroundTile = Instantiate(tilePrefab, tempPosition, Quaternion.identity) as GameObject;
                 backgroundTile.transform.SetParent(this.transform);
                 backgroundTile.name = "( " + x + "," + y + ")";

                 allTiles[x, y] = backgroundTile;               
             }
         }

但是瓷砖放置在错误的地方。它们应该在屏幕的左下方彼此相邻放置,但只有第一个图块位于正确的位置。

如何将所有瓷砖正确放置在板上?

编辑 这是我要实例化的预制件: enter image description here

这就是我得到的:

enter image description here

这就是我想要得到的:

enter image description here

谢谢。

2 个答案:

答案 0 :(得分:0)

我没有完全查看您的代码,但是尝试一下;

for (int x = 0; x < width; x++)
         {
             for (int y = 0; y < height; y++)
             {                
                 Vector3 tempPosition = camera.ViewportToWorldPoint(new Vector3(x, y, camera.nearClipPlane));                    
                 GameObject backgroundTile = Instantiate(tilePrefab, tempPosition, Quaternion.identity,this.transform) as GameObject;

                 backgroundTile.name = "( " + x + "," + y + ")";

                 allTiles[x, y] = backgroundTile;               
             }
         }

尝试一下,如果在实例化后设置了parent,有时UI会产生愚蠢的事情。因此,最好在这样实例化时设置setparent;

GameObject backgroundTile = Instantiate(tilePrefab, tempPosition, Quaternion.identity,this.transform) as GameObject;

答案 1 :(得分:0)

如果是用于构建UI元素,则根据您要执行的操作使用网格组件或垂直/水平布局。只需将实例化的元素设置为将处理布局的网格父级