I’m working through a tutorial from a few years ago so it’s doubtful I’d get any help from the original video, so I turn to you. This script is attached to an image inside of a canvas, inside of another canvas.
At this point in the video, the instantiated prefabs are inside of the image, but I must be missing something. I would rather have the prefabs instantiate on a panel, but I’m getting the same results.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
RectTransform inventorySlotRect;
float inventoryWidth, inventoryHeight;
public int slots;
public int rows;
public float slotPaddingLeft, slotPaddingTop;
public float slotSize;
//public Transform InventoryDisplayParent;
public GameObject InventorySlotPrefab;
List<GameObject> allSlotsList;
// Start is called before the first frame update
void Start()
{
CreateInventoryLayout();
}
// Update is called once per frame
void Update()
{
}
void CreateInventoryLayout()
{
allSlotsList = new List<GameObject>();
inventoryWidth = (slots / rows) * (slotSize + slotPaddingLeft) +slotPaddingLeft;
inventoryHeight = rows * (slotSize + slotPaddingTop) + slotPaddingTop;
int collumns= slots/rows;
inventorySlotRect = GetComponent<RectTransform>();
inventorySlotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, inventoryWidth);
inventorySlotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, inventoryHeight);
for(int y=0; y<rows; y++)
{
for(int x=0; x<collumns; x++)
{
GameObject newInventorySlot = (GameObject)Instantiate(InventorySlotPrefab);
RectTransform inventorySlotRect = newInventorySlot.GetComponent<RectTransform>();
newInventorySlot.name = "Slot";
newInventorySlot.transform.SetParent(this.transform.parent);
inventorySlotRect.localPosition = inventorySlotRect.localPosition + new Vector3(slotPaddingLeft * (x + 1) + (slotSize * x), -slotPaddingTop *(y +1)-(slotSize *y)) ;
//inventorySlotRect.transform.SetParent(InventoryDisplayParent);
inventorySlotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize);
inventorySlotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize);
allSlotsList.Add(newInventorySlot);
}
}
}
}
Would someone give this a once over and see where the problem lies?
All anchor points are set to upper left and I’ve tried every layout component to no avail.
Thanks!