- Unity 2018 Cookbook(Third Edition)
- Matt Smith
- 371字
- 2025-02-23 18:56:38
How to do it...
To automatically populate a panel using UI Grid Layout Groups to follow these steps:
- Create a new folder named Prefabs. In this folder, create a new empty prefab named panel-inventory-slot.
- From the Hierarchy panel, drag the GameObject Panel-inventory-slot into your new empty prefab named panel-inventory-slot. This prefab should now turn blue, showing it is populated.
- In the Hierarchy panel, delete the three GameObjects Panel-inventory-slot / (1) / (2).
- Un-child Text-title from Panel-stars. Set the Pos-X position of Panel-stars. To 130 - so that the panel is now to the right of the text Stars.
- With the panel Panel-stars selected in the Hierarchy panel, add a grid layout group component (Add Component | Layout | Grid Layout Group). Set Cell Size to 50 x 50 and Spacing to 5 x 5. Also, set the Child Alignment to Middle Center (so our icons will have even spacing at the far left and right), as shown in the following screenshot:

- Replace the C# script PlayerInventoryDisplay in GameObject player-SpaceGirl with the following code:
using UnityEngine; using System.Collections; using UnityEngine.UI; [RequireComponent(typeof(PlayerInventory))] public class PlayerInventoryDisplay : MonoBehaviour { const int NUM_INVENTORY_SLOTS = 5; public GameObject panelSlotGrid; public GameObject starSlotPrefab; private PickupUI[] slots = new PickupUI[NUM_INVENTORY_SLOTS]; void Awake() { float width = 50 + (NUM_INVENTORY_SLOTS * 50); panelSlotGrid.GetComponent<RectTransform>().SetSizeWithCurrentAnchors( RectTransform.Axis.Horizontal, width ); for(int i=0; i < NUM_INVENTORY_SLOTS; i++){ GameObject starSlotGO = (GameObject) Instantiate(starSlotPrefab); starSlotGO.transform.SetParent(panelSlotGrid.transform); starSlotGO.transform.localScale = new Vector3(1,1,1); slots[i] = starSlotGO.GetComponent<PickupUI>(); } } public void OnChangeStarTotal(int starTotal) { for(int i = 0; i < NUM_INVENTORY_SLOTS; i++){ PickupUI slot = slots[i]; if(i < starTotal) slot.DisplayColorIcon(); else slot.DisplayGreyIcon(); } } }
- Ensure GameObject player-girl1 is selected in the Hierarchy. Then drag from the Project panel GameObject Panel-stars into the Player Inventory Display (Script) variable Panel-slot-grid, in the Inspector.
- With GameObject player-girl1 selected in the Hierarchy, drag from the Project panel prefab panel-inventory-slot into Player Inventory Display (Script) the variable Star Slot Prefab, in the Inspector. Steps 7 and 8 are illustrated in this screenshot:

- Edit the script class PlayerInventoryDisplay to set the constant NUM_INVENTORY_SLOTS to have 10 or 15 slots. So some can only be seen when using the horizontal scroll bar.
- Save the scene and play the game. As you pick up stars, you should see more of the grey stars change to yellow in the inventory display.