💻

UIToolKitで円型ゲージを作ってみる上編

2024/12/17に公開

初めに

UnityのUIToolkitにはデフォルトで円型のゲージやプログレスバーが用意されていません。現在、いくつかのプロジェクトでこれらが必要となったため、自作することにしました。
成果物は以下のGitHubリポジトリに公開していきます。今現在は何も上がっていません

https://github.com/tsutsumikirku/-CircularGauge

何はともあれとりあえず作ってみよう

参考資料

今回参考にしたのは、Unity公式ドキュメントに掲載されている円型ゲージに関する記事です。

URL:https://docs.unity3d.com/6000.0/Documentation/Manual/UIE-radial-progress.html

記事を読んで気づいたこと

この記事を読む中で、「UIElement」の名前空間にVertexという構造体が存在し、頂点情報を格納できることを知りました。この構造体と頂点を指定する配列を活用することで、メッシュを作成し、それをVisualElementとして利用できるとのことです。

これを理解すると、円型のゲージ自体は意外と簡単に作れるかもしれない、と感じました。

しかし、公式のリポジトリにある完成形を試してみると、少々使いにくい印象を受けました。
例えば、360度ではない「虹」のような円型ゲージを作る際に問題が発生しました。

設定を工夫すれば解決できると思いますが、もっと簡単に柔軟な調整ができるようにしたいと考えています。

メッシュを使った表示の確認

まずは、メッシュの表示方法と仕組みを理解するため、簡単なメッシュを用いて試作してみました。

できた!!

今回のコードはこちら

using UnityEngine;
using UnityEngine.UIElements;

    public partial class RadiusTest : VisualElement
    {
        public new class UxmlFactory : UxmlFactory<RadiusTest, UxmlTraits> { }

        public RadiusTest()
        {
            this.style.width = 200;   
            this.style.height = 200;
            this.style.overflow = Overflow.Visible;
            generateVisualContent += VisualContent;
        }

        void VisualContent(MeshGenerationContext context)
        {
            Vertex[] vertices = new Vertex[3];
            ushort[] indices = new ushort[3];
            var width = this.resolvedStyle.width;
            var height = this.resolvedStyle.height;
            vertices[0] = new Vertex { position = new Vector2(width * 0.25f, height * 0.25f), tint = Color.red };   
            vertices[1] = new Vertex { position = new Vector2(width * 0.75f, height * 0.25f), tint = Color.green };
            vertices[2] = new Vertex { position = new Vector2(width * 0.5f, height * 0.75f), tint = Color.blue };  
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            var meshWriteData = context.Allocate(vertices.Length, indices.Length);
            meshWriteData.SetAllVertices(vertices);
            meshWriteData.SetAllIndices(indices);
        }
}

とりあえず理解したことはVertexには頂点の座標とその頂点のカラーを保存するそしてushortに三角形を構成するために、頂点をどの順番で結ぶかを指定する。
絵にかくとこんな感じ?

とりあえずメッシュを生成してVisualElementにする方法は理解した。

今回はここまでにする

中編 作成中
下編

Discussion