I was wondering if someone can shed some light on this.
I have a prefab that contains a GridLayoutView with a predetermined cell size with an image in it. When I add this to my canvas in unity it works fine. However, if I add the same prefab using the below code, it changes the size of the cells and the image, as well as the location on the canvas. It does not change the cell size property though.
Why is this?
public void CreateGrid(GameObject levelContainer)
{
mapContainer.transform.SetParent(levelContainer.transform);
var total = tiles.Count;
var column = 0;
var row = 0;
for (var i = 0; i < total; i++)
{
column = i % columns;
mapContainer.GetComponent<UnityEngine.UI.GridLayoutGroup>().constraintCount = columns;
var newX = column;
var newY = -row;
var go = Instantiate(Resources.Load("Prefabs\\TilePrefab")) as GameObject;
go.name = "Tile " + i;
go.transform.position = new Vector3(newX, newY, 0);
go.transform.SetParent(mapContainer.transform);
var tile = tiles[i];
var spriteID = tile.id;
if (spriteID >= 0)
{
SpriteRenderer IMG = go.GetComponent<Image>();
IMG.sprite = GetTextureFromCode(tile.tileCode);
}
if (column == (columns - 1))
{
row++;
}
}
}
I’ve experienced a similar thing, where instantiating a canvas object, then it being resized somehow.
I think what it happens for, is when you add a prefab of a UI element to a canvas (say by drag and dropping it there) it will have been parented directly to the canvas and maintain its scaling and stuff. But when you instantiate it, and then later parent it to the canvas, this forces the canvas scaling to try and adjust this UI element somehow, or at least that is my understanding from testing I had done.
I guess the best thing to do is just rescale the UI element after you have instantiated it, or alternatively, try parenting the object when you do the instantiation call instead of in a later line (not sure that will help or not, can’t remember!).
Thanks for getting back to me. I have solved the issue by placing the following code at the end of the import. Just seems messy and counter-intuitive to what a prefab should do. I will mark this as solved.
var RT = mapContainer.transform.parent.GetComponent<RectTransform>();
RT.localScale = new Vector3(1, 1, 1);
RT.localPosition = new Vector3(0, 0, 0);
RT.offsetMin = new Vector2(0, 0);
RT.offsetMax = new Vector2(0, 0);