1
\$\begingroup\$

I created some MenuItemfunctions for navigating, which are currently displayed on the menu toolbar. The C# code:

using UnityEditor;
using UnityEngine;

public class Menu : MonoBehaviour {

static void rotateView(Quaternion rotation) {
    SceneView.lastActiveSceneView.LookAt(SceneView.lastActiveSceneView.pivot, rotation);

    SceneView.lastActiveSceneView.Repaint();
}

[MenuItem("View/Front _1")] // FRONT
static void FrontView() {
    rotateView(Quaternion.Euler(0, 180, 0));
}

[MenuItem("View/Back &1")] // BACK
static void BackView() {
    rotateView(Quaternion.Euler(0, 0, 0));
}

// Few more similar functions

}

I came from Blender, where there are shortcuts opening a context menu on the cursor position like this one, opened after pressing U:

Blender context menu

What I want to do is displaying a context menu after pressing P which would display a list of implemented MenuItems. Is something like this possible in Unity?

\$\endgroup\$
0
\$\begingroup\$

You can use ScreenToWorldPoint to convert your mouse positions to 3D coordinates.

Also ScreenToViewportPoint converts your mouse positions to normalized 2D coordinates on current viewport.

Usage:

ReferenceCamera.ScreenToWorldPoint(mouseX,mouseY,distanceFromCamera)

Where

mouseX = ReferenceCamera.ScreenToViewportPoint(Input.mousePosition).x

mouseY = ReferenceCamera.ScreenToViewportPoint(Input.mousePosition).y

  • ScreenToViewportPoint gives you a value between 0 and 1 normalized for the screen you are playing in. Very useful for placement of UI elements on HUD. This is probably what you are looking for.
  • ScreenToWorldPoint is used to get world position. This is useful if you want to create an explosion at x distance from screen for a game with orthographic projection.

Create a HUD. Attach it to camera. Check ScreenToViewportPoint and calculate if the menu should spawn to bottom-right/bottom-left/top-left/top-right so it doesnt go out of bounds. You can track selections through same method.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.