- Home /
GUILayout Context Menu on Right Click - Not Working!
This is a Unity*2D* Project. I am using OnMouseOver() for right clicks.
I've created a GUILayout Context Menu which is supposed to pop up when the user right clicks on an object.
Here is the code for the OnGUI() function in the module which is attached to the object i am right clicking on:
void OnGUI() {
GUI.skin.button.normal.background = ContextMenuItemTexture;
GUI.skin.button.hover.background = ContextMenuItemTexture;
GUI.skin.button.active.background = ContextMenuItemTexture;
if (ShowContextMenu) {
GUILayout.BeginArea(new Rect(ContextMenuPosition.x,
ContextMenuPosition.y,
ContextMenuItemTexture.width,
ContextMenuItems.Count <= 5f ? ContextMenuItems.Count : 5f));
{
GUILayout.BeginScrollView(scrollPosition);
{
foreach (KeyValuePair<ContextMenuAction, string> item in ContextMenuItems) {
if (GUILayout.Button(item.Value)) {
item.Key();
ShowContextMenu = false;
}
}
}
GUILayout.EndScrollView();
}
GUILayout.EndArea();
}
}
There is 1 item in the ContextMenuItems dictionary. The problem is that a GUILayour Button is not showing up at all, even before i changed the background texture to a texture i provided. No default button showed up, or anything.
The ContextMenuPosition is calculated in the Update() method like so:
if (RightClicked) {
ShowContextMenu = true;
ContextMenuPosition.x = Input.GetAxis("Mouse X");
ContextMenuPosition.y = Input.GetAxis("Mouse Y");
}
Here are the OnMouse____() Methods used:
void OnMouseDown() {
LeftClicked = true;
}
void OnMouseUp() {
LeftClicked = false;
}
void OnMouseOver() {
if (Input.GetMouseButton(1)) {
RightClicked = true;
} else if (!Input.GetMouseButton(1)) {
RightClicked = false;
}
}
What is wrong with my GUI code? How can i make the context menu appear? Keep in mind that this is NOT attached to a camera, but to an object that the user right clicks on.
Answer by Maerig · Jun 16, 2014 at 09:30 AM
Hey ! In OnGUI
, I think you simply forgot to multiply this value
ContextMenuItems.Count <= 5f ? ContextMenuItems.Count : 5f
by
ContextMenuItemTexture.height
I hope that enough will fix it !