0
\$\begingroup\$

I'm creating a simple match three game in Unity. I've opted to use Unity's UI system as it takes care of resolution scaling for me. The project is quite simple, at runtime I am programmatically creating an 8x8 grid of tiles via the script below. This script is attached to an empty Game Object residing within a canvas.

public class GameBoard : MonoBehaviour
{

    public int BoardSize = 8;
    public List<GameObject> TileSet; 

    void Start ()
    {
        for (float y = 0; y < BoardSize; y++)
        {
            for (float x = 0; x < BoardSize; x++)
            {
                int tileIndex = Random.Range(0, TileSet.Count - 1);
                Vector3 position = new Vector3(x, y, 0.0f);
                GameObject newTile = Instantiate(TileSet[tileIndex], position, this.transform.rotation, this.transform);

            }
        }
    }

}

As you can see, the first tile is being positioned at a Vector3 of 0, 0, 0. The second at 0, 1, 0, and so on. At runtime this translates to Rect Transforms of 0, 0, -9720, and 108, 0, -9720 respectively.

Where is 108 coming from, and why is the Z an arbitrary -9720 when it should be a constant zero?

I suspect this must be due to canvas scaling, so I have attached an image of the canvas's settings. Canvas's settings.

\$\endgroup\$
3
  • \$\begingroup\$ I'm not really sure how canvas scale things. But, if you're using RectTransform, you should use AnchoredPosition for positioning objects. \$\endgroup\$ Jul 31, 2018 at 5:19
  • \$\begingroup\$ Interesting that 9720 = 9 * 1080. \$\endgroup\$
    – 3Dave
    Jul 31, 2018 at 17:38
  • \$\begingroup\$ What's the value of this.transform.translation when your script executes the GameObject newTile = Instantiate(...) line? \$\endgroup\$
    – 3Dave
    Jul 31, 2018 at 17:40

1 Answer 1

0
\$\begingroup\$

I tried every different way of instantiating a game object and the value of pos z would only be correct for the first one instantiated. The only thing that would work for me is Instantiating the Game Object and then setting the localPosition.

It would look something like this.

int tileIndex = Random.Range(0, TileSet.Count - 1);
Vector3 position = new Vector3(x, y, 0.0f);
GameObject newTile = Instantiate(TileSet[tileIndex], position, this.transform.rotation, this.transform); 
newTile.transform.localPosition = position; // Don't set position, set localPosition
\$\endgroup\$
1
  • 1
    \$\begingroup\$ This results in what I would expect... very strange. I'd be curious to find out why this functions so strangely. \$\endgroup\$
    – user99319
    Jul 31, 2018 at 2:31

You must log in to answer this question.