Skip to content

Creating a Mouseless Context Menu in Unity

I was prototyping a 2D Side Scroller game in Unity a week ago and started implementing an Inventory System (Equipments, slots, etc…).
Unfortunately, Unity didn’t have a Context Menu out of the box so I searched a bit and found this, which helped me get an idea of how to implement one as well as make it completley mouseless, since my game was mouseless itself.

Preparing the UI

A panel for our Context Menu

The first step is to create a panel (in a canvas as usual) for our Context Menu, you can customize it however you like.
The panel will have to have these components to save us some code:

A VerticalLayoutGroup so that the items take the whole width of the menu.
A ContentSizeFitter with VerticalFit set to Min Size so that the Context Menu’s height is always the sum of its children.

A button prefab for our Context Menu Items

Next, we’ll have to create a prefab of how the items will be shown in the menu.
Using a Button makes things easier since it has a onClick .

The button has to have a LayoutElement set to a height you want, since we’re using a VerticalLayoutGroup in its parent.

Scripts

Items

We will represent each item in the menu with the following class:

Menu

We’ll need a couple of fields:

Unity methods:

Showing the menu:

Hiding the menu:

I got a problem when hiding the menu directly if the player presses Space to click items.
Since Space was the key the player needed to press on an Item slot to show the menu, it would hide the menu and show it directly.

To fix this, I ended up hiding the menu the next frame (after the Space event is fired):

Usage Example

I will show you how I personally use this for my Inventory System.

I have a ItemSlotBehaviour that handles each slot in the inventory.
When the player presses Space:

GetContextMenuItems() simply returns a list of ContextMenuItem depending on the type of item (usable, equipment, others…).

For example, if the item is an equipable:

The action is simply to equip the item using the Inventory System.

Conclusion

I hope this post helps someone in the future and I’d like to thank Experion again for his answer in Stackoverflow as his idea was my starting point.
If you have any suggestions, feel free to comment/message me.
See you around!

Published inProgrammingUnity 2D/3D

Leave a Reply

avatar
  Subscribe  
Notify of