LoginSignup
5
5

More than 3 years have passed since last update.

【Unity】UI ToolkitのMouseDown・MouseUpの最小実装

Last updated at Posted at 2021-01-05

【Unity】UI ToolkitをランタイムUIとして使ってみるに引き続き、
Unityの次世代UIシステムにあたるUI Toolkitについて調査していきます。

あくまでランタイムUIとして使う想定の検証です。

今回作るもの

マウス押下している時に色が変わるサンプルを作っていきます。
demo.gif

環境

  • Unity2020.2.0f1
  • UI Toolkit 1.0.0-Preview.13

PointerDownEventとPointerUpEventを使う

MouseDown・MouseUpに反応するVisualElementに対してイベントを登録(RegisterCallback)していきます。

uxmlファイルから見ていきます。

MouseDownUpTest.uxml
<ui:UXML xmlns:ui="UnityEngine.UIElements" editor-extension-mode="False">
    <ui:VisualElement name="container" style="height: 100%; width: 100%; background-color: rgba(255, 252, 0, 255);" />
</ui:UXML>

containerという名前のVisualElementが1つだけ全画面に配置してあるシンプルな構成です。

C#側からVisualElementにイベント登録

C#のソースコードです。

MouseDownUpTest.cs
// _documentはUIDocumentのこと
var visualTree = _document.rootVisualElement;

// VisualElement : "conainer"をvisualTreeから検索して取得
VisualElement container = visualTree.Q("container");

// イベント登録
container.RegisterCallback<PointerDownEvent>(OnPointerDown);
container.RegisterCallback<PointerUpEvent>(OnPointerUp);

VisualElementであるcontainerを取得して、RegisterCallbackメソッドでイベントを登録しています。

コールバック先でイベントターゲットのVisualElementを取得する

MouseDownUpTest.cs
// MouseUpしたら色を赤色にする
private void OnPointerDown(PointerDownEvent evt)
{
    var ve = (VisualElement) evt.target;
    ve.style.backgroundColor = Color.red;
}

// MouseUpしたら色を黄色にする
private void OnPointerUp(PointerUpEvent evt)
{
    var ve = (VisualElement) evt.target;
    ve.style.backgroundColor = Color.yellow;
}

ポイントは(VisualElement) evt.targetの部分でVisualElementにキャストしているところでしょうか。公式サンプルがこうなってるので、それにならった形を取りました。

EventSystem(UI Toolkit)が必ず必要

「イベントが通知されないな〜??」

と思った時はEventSystemがシーンに配置してあるかチェックしてみましょう。
必ずシーンに1つ必要です。

最後に

以上UI ToolkitにおけるMouseDown・MouseUpの最小実装でした。
ソースコード全文はGistにアップしています。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5