This script allows you to scroll through a list of inventory items - and select them - by clicking on dedicated "Up", "Down" and "Select" buttons, rather than clicking on the item list itself.
To use it:
- Create a new Unity UI Canvas with a list of Buttons for each item slot, as well as separated Up, Down and Select buttons
- Parent the item slots button to a new GameObject, and attach a Canvas Group component to the parent
- In the Canvas Group, uncheck "Blocks Raycasts"
- Copy/paste the code below into a new C# script named IndirectlySelectItem.cs, and attach it to the root Canvas
- For each of the Up, Down and Select buttons, create a new OnClick event. Map this to the IndirectlySelectItem component's OnClick_Up, OnClick_Down and OnClick_Select functions respectively.
- Make the UI Canvas a prefab
- Create a new Menu in AC's Menu Manager, set its "Source" to "Unity UI Prefab", and assign the UI Canvas prefab as its "Linked Canvas prefab"
- Create a new InventoryBox element, set its "Maxiumum number of slots" to match the number of item slots in the UI, and link each item slot to its corresponding UI button
IndirectlySelectItems.cs:
using UnityEngine;
using AC;
public class IndirectlySelectItems : MonoBehaviour
{
#region Variables
private int selectedIndex = -1;
private MenuInventoryBox inventoryBox;
[SerializeField] private Color normalColor = Color.white;
[SerializeField] private Color highlightColor = Color.blue;
#endregion
#region UnityStandards
private void OnEnable ()
{
if (KickStarter.playerMenus != null)
{
Menu thisMenu = KickStarter.playerMenus.GetMenuWithCanvas (GetComponent <Canvas>());
inventoryBox = thisMenu.GetElementWithName ("InventoryBox") as MenuInventoryBox;
SetSelectedIndex (0);
}
}
private void OnGUI ()
{
GUILayout.BeginVertical ("Button");
GUILayout.Label (selectedIndex.ToString ());
GUILayout.EndVertical ();
}
#endregion
#region PublicFunctions
public void OnClick_Select ()
{
InvItem selectedItem = inventoryBox.GetItem (selectedIndex);
if (selectedItem != null)
{
selectedItem.RunUseInteraction ();
}
}
public void OnClick_Up ()
{
int newSelectedIndex = selectedIndex - 1;
if (newSelectedIndex < 0)
{
newSelectedIndex = 0;
inventoryBox.Shift (AC_ShiftInventory.ShiftPrevious, 1);
}
SetSelectedIndex (newSelectedIndex);
}
public void OnClick_Down ()
{
int newSelectedIndex = selectedIndex + 1;;
if (newSelectedIndex >= inventoryBox.GetNumSlots ())
{
newSelectedIndex = inventoryBox.GetNumSlots () - 1;
inventoryBox.Shift (AC_ShiftInventory.ShiftNext, 1);
}
SetSelectedIndex (newSelectedIndex);
}
#endregion
#region PrivateFunctions
private void SetSelectedIndex (int value)
{
if (selectedIndex != value)
{
if (selectedIndex >= 0 && selectedIndex < inventoryBox.GetNumSlots ())
{
inventoryBox.uiSlots[selectedIndex].SetColour (normalColor);
}
if (value >= 0 && value < inventoryBox.GetNumSlots ())
{
inventoryBox.uiSlots[value].SetColour (highlightColor);;
}
selectedIndex = value;
}
}
#endregion
}