Operating with the mouse (Input System Package Version)

Page update date :
Page creation date :

Verification environment

Windows
  • Windows 11
Unity Editor
  • 2020.3.25f1
Input System Package
  • 1.2.0

Prerequisites for this tip

The following settings have been made in advance as a premise for the description of this tip.

Get the mouse position

The position of the mouse on the game screen can Mouse.position be obtained in . Here, I would like to display the location information.

Places a text object on the Canvas that displays mouse information.

Mouse information is retrieved by scripting. In this case, we will create a script file called in the project MouseInfo .

Enter the script as follows:

using System.Text;              // 追加
using UnityEngine;
using UnityEngine.InputSystem;  // 追加
using UnityEngine.UI;           // 追加

public class MouseInfo : MonoBehaviour
{
  /// <summary>情報を表示するテキストオブジェクト。</summary>
  [SerializeField] private Text TextObject;

  private StringBuilder Builder = new StringBuilder();

  // 更新はフレームごとに1回呼び出されます
  void Update()
  {
    if (TextObject == null)
    {
      Debug.Log($"{nameof(TextObject)} が null です。");
      TextObject.text = "";
      return;
    }

    var mouse = Mouse.current;
    if (mouse == null)
    {
      Debug.Log("マウスがありません。");
      TextObject.text = "";
      return;
    }

    Builder.Clear();

    // マウスの位置を取得する
    Builder.AppendLine($"Mouse.position={mouse.position.ReadValue()}");

    TextObject.text = Builder.ToString();
  }
}

Mouse.currentYou can get information about the currently active mouse. Mouse.position has the current position of the mouse in , so ReadValue you can get the value in the form by Vector2 using the Vector2Control method.

The acquired mouse position is set to a text object. StringBuilder Don't worry too much about using , as it's for adding later.

After EventSystem you save the script, attach it to the object. Text Object is set to a text object to display information about.

Try running the game and moving the mouse. I think the mouse position will appear on the screen in real time.

By the way, the coordinates of the mouse position are (0, 0) in the lower left corner of the game screen. The X axis (left and right) becomes positive as you go to the right and negative as you go to the left. The Y-axis (up and down) becomes positive as you go up and negative as you go down. Therefore, the maximum value of each axis is in the upper right corner of the game screen.

Also, please note that this coordinate is only for the game screen space, so the pixel size in the game and the pixel size of the device's screen coordinates may not match.

Get the amount of scroll of the wheel

Scrolling with the mouse wheel can also be retrieved in the script. The scrolling amount Mouse.scroll can be obtained with . Unlike the mouse position, you can only get the amount scrolled instantaneously. Note that you can't get how far you've scrolled.

I will add it to the scroll operation I created MouseInfo earlier.

// 省略

public class MouseInfo : MonoBehaviour
{
  // 省略

  /// <summary>スクロールした量を保持する。</summary>
  private Vector2 ScrollValue = Vector2.zero;

  // 更新はフレームごとに1回呼び出されます
  void Update()
  {
    // 省略

    // スクロール量を取得し保持する
    ScrollValue += mouse.scroll.ReadValue();

    Builder.Clear();

    // マウスの位置を取得する
    Builder.AppendLine($"Mouse.position={mouse.position.ReadValue()}");
    // スクロール量を表示
    Builder.AppendLine($"ScrollValue={ScrollValue}");

    TextObject.text = Builder.ToString();
  }
}

Mouse.current does not hold the amount scrolled so far, so Define a dedicated field ScrollValue to hold the scrolling amount.

Mouse.scroll Then, you can get the scrolled amount at that moment, so we will accumulate that value. For example, if ScrollValue you scroll the wheel twice, the amount of scrolled twice will be retained.

The rest is to display this value as text.

Now run the game and spin the wheel. I think you will see the amount of scrolling.

Mouse.scrollVector2 has a value of , but if it is a vertical scroll-only wheel, I think only the value of Y will be set.

By the way, if you scroll down, the value will go up and down in 120 units. This is a value defined by Windows, so the number may change depending on other environments and mouse types.

Determine when a mouse button is clicked

Here, I would like to move a sample that displays text at the position where the left mouse button is clicked. The timing of clicking can be determined by properties in the same way as wasPressedThisFrame keyboard keys.

First, place a text object for moving. The size and position are appropriate.

Create a script for the click process. MouseButtonClick Leave the name as .

The script looks like this:

using UnityEngine;
using UnityEngine.InputSystem;  // 追加
using UnityEngine.UI;           // 追加

public class MouseButtonClick : MonoBehaviour
{
  /// <summary>情報を表示するテキストオブジェクト。</summary>
  [SerializeField] private Text TextObject;
  [SerializeField] private Canvas CanvasObject;

  /// <summary>Canvas の RectTransform の参照です。</summary>
  private RectTransform CanvasRect;

  // 最初のフレーム更新の前に開始が呼び出されます
  void Start()
  {
    if (CanvasObject == null)
    {
      Debug.Log($"{nameof(CanvasObject)} が null です。");
      return;
    }

    // Canvas から RectTransform を取得しておきます。
    CanvasRect = CanvasObject.GetComponent<RectTransform>();
  }

  // 更新はフレームごとに1回呼び出されます
  void Update()
  {
    if (TextObject == null)
    {
      Debug.Log($"{nameof(TextObject)} が null です。");
      return;
    }
    if (CanvasObject == null)
    {
      Debug.Log($"{nameof(CanvasObject)} が null です。");
      return;
    }

    var mouse = Mouse.current;
    if (mouse == null)
    {
      Debug.Log("マウスがありません。");
      return;
    }

    var transform = TextObject.transform;

    // マウスの位置を取得する
    var mousePosition = mouse.position.ReadValue();

    // マウスの位置を Canvas の座標に変換する
    var mouseOnCanvas = new Vector2(mousePosition.x - CanvasRect.sizeDelta.x / 2, mousePosition.y - CanvasRect.sizeDelta.y / 2);

    // 左ボタンがクリックしたタイミングか判定
    if (mouse.leftButton.wasPressedThisFrame)
    {
      transform.localPosition = mouseOnCanvas;
    }
  }
}

I perform the process of moving the text object to the clicked position. The local position of the UI object is the coordinate of the Canvas, so it is different from the position of the mouse, which is the screen coordinate.

Since the origin of the Canvas (0, 0) is in the center,RectTransform.sizeDelta use to get half the size of the Canvas. The origin of the mouse coordinates is shifted to the center.

You can determine whether or not mouse.xxxxxxxx.wasPressedThisFrame you clicked, and return only true the moment you click. If you click and hold the button, it will continue to return until you false click it again.

After EventSystem you save the script, attach it to . This time, we will also use Canvas, so set the Canvas and the text object.

Try running the game and see if the text object moves to the clicked location. Since it only processes the moment it is clicked, the text object does not move even if you move the mouse while clicking.

Determine when you release the mouse button

Although it is not listed as a sample, wasPressedThisFrame you can determine the timing of release by using instead of wasReleasedThisFrame .

Judge while clicking the button

mouse.xxxxxxxx.isPressed to continue to return as long true as you click the button. Here, I would like to rotate the text while pressing the right button.

The script is diverted from the left-click one. Modify it as follows:

// 省略

public class MouseButtonClick : MonoBehaviour
{
  // 省略

  // 更新はフレームごとに1回呼び出されます
  void Update()
  {
    // 省略

    // 右ボタンを押している間はオブジェクトを回転させる
    if (mouse.rightButton.isPressed)
    {
      transform.Rotate(0, 0, 1);
    }
  }
}

After saving the script, run it to check it. The object continues to rotate as long as the right button is pressed.