0
votes

I instantiate a Board GameObject using this code:

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

Then I try to fill this board by instantiating Tiles GameObjects with loop:

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;               
             }
         }

But the tiles are placed on wrong place. They should be placed one next to each other at the bottom left of the screen but only the first Tile is at correct position.

How can I get all tiles correctly placed on the board?

EDIT Here is the prefab I am instantiating: enter image description here

This is what I get:

enter image description here

and this is what I am trying to get:

enter image description here

Thank you.

2
its position will be offset by anything you did in the prefab - BugFinder
@BugFinder I added a screenshot of my prefab. - Johny
What exactly turns out to be wrong with the position of the others - BugFinder
@BugFinder I added more screenshots showing the result I get and what I am trying to do. - Johny
So it looks like as simple as your blocks you're putting down arent 1 unit wide, therefore when you put them down 1 unit apart.... thats what you get.. So, you need to use the size of your blocks to multiply where to put them. - BugFinder

2 Answers

0
votes

I did not fully look at your code but try this;

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;               
             }
         }

give it a try, sometimes UI makes stupid things if you set parent after you instantiate. So it is better to setparent when you instantiate like this;

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

If it is for building UI element, I would use the grid component or the vertical/horizontal layout depending on what you want to do. Just set the instantiated element to the grid parent that will take care of the layout