Beispiel #1
0
    // TODO: limit number of colums, thus giving set size of the inventory
    //          - could add a check before creating the newItem, and breaking from the loop if reached.
    void Refresh()
    {
        foreach (Transform child in slotContainer)
        {
            if (child != itemTemplate)
            {
                Destroy(child.gameObject);
            }
        }

        // Create the cells in the inventory
        int   row     = 0;        // used for limiting the number of cells a row can have
        int   col     = 0;        // used for limiting the number of rows in the inventory
        int   xPos    = 40;       // starting location of the first cell in the canvas
        int   yPos    = -30;      // starting location of the first cell in the canvas
        int   spacing = 10;       // space between each cell in the (x) and (y) direction
        float scale   = .3f;      // scale for the items in the inventory

        int   cells        = 4;   // for easier adjustment of the number of cells
        float itemCellSize = 40f; // size of each cell
        int   imageSize    = 10;

        foreach (Item item in inventory.GetItems())
        {
            // Create a new game object within the container for slots, in the form of the item template previously created
            // Then set its position in the canvas
            RectTransform newItem = Instantiate(itemTemplate, slotContainer).GetComponent <RectTransform>();
            newItem.gameObject.SetActive(true);
            newItem.anchoredPosition = new Vector2(xPos + (row * (itemCellSize + spacing)), yPos - (col * (itemCellSize + (spacing - (spacing * 1 / 5)))));
            newItem.localScale       = new Vector2(scale, scale);

            // Create a child to hold the image of the item that will be displayed in the inventory slot
            Image image = newItem.Find("Image").GetComponent <Image>();
            image.sprite = item.GetSprite();
            image.transform.localScale = new Vector3(imageSize, imageSize, imageSize);

            // Update the Text of items in the inventory, depending on quantity
            Text text = newItem.Find("itemText").GetComponent <Text>();
            if (item.quantity > 1)
            {
                text.text = item.quantity.ToString();
            }
            else
            {
                text.text = "";
            }

            // Inventory size check
            row++;
            if (row > cells)
            {
                row = 0;
                col++;
            }
        }
    }