GUI」タグアーカイブ

文字列に合わせたUI.Textのサイズを取得する方法

UnityのUI.Textで、実際にテキストを表示した際のサイズが知りたい場合はpreferredWidthpreferredHeightを使って調べることができるそうです。

使い方

Text text;

float width = text.preferredWidth;
float height = text.preferredHeight;

テキストのサイズに合わせてUIを調整したい場合に便利かなと思います。

TextMeshPro

TexhMeshProの場合もpreferredWidthpreferredHeightを使って実際のサイズを調べることができるようです。

使い方

TMPro.TextMeshProUGUI text;

float width = text.preferredWidth;
float height = text.preferredHeight;

リンク

Unity – Scripting API: ILayoutElement
https://docs.unity3d.com/ScriptReference/UI.ILayoutElement.html

Class TextMeshProUGUI | TextMeshPro | 1.5.6
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.5/api/TMPro.TextMeshProUGUI.html

UnityのUIに自分で作ったメッシュを表示

UnityのUI上に自分で作ったメッシュを表示したい場合はOnPopulateMeshを使うとできるみたいです。

public class Example : Graphic
{
  protected override void OnPopulateMesh(VertexHelper vh)
  {
    vh.AddVert(new Vector3(0, 0), Color.white, new Vector2(0f, 0f));
    vh.AddVert(new Vector3(0, 100), Color.white, new Vector2(0f, 1f));
    vh.AddVert(new Vector3(100, 100), Color.white, new Vector2(1f, 1f));
    vh.AddVert(new Vector3(100, 0), Color.white, new Vector2(1f, 0f));
    vh.AddTriangle(0, 1, 2);
    vh.AddTriangle(2, 3, 0);
  }
}

UI上にライン(直線)を引こうと思ってお手軽な方法を探していたのですが、Line Rendererは少し使い勝手が良くなくて結局自分でメッシュを作るのが一番簡単かなという感じです。

リンク

Unity – Scripting API: UI.Graphic.OnPopulateMesh
https://docs.unity3d.com/ScriptReference/UI.Graphic.OnPopulateMesh.html

Unity – Scripting API: Graphic
https://docs.unity3d.com/ScriptReference/UI.Graphic.html

Unity – Scripting API: LineRenderer
https://docs.unity3d.com/ScriptReference/LineRenderer.html

UnityのスクリプトでUIを最前面や最背面に移動する方法

UnityのCanvas内に複数のUIがある場合、Hierarchyの順に重なって表示されるようになっています。 これを前面や背面に移動させたい場合は、Transform.SetAsLastSiblingTransform.SetAsFirstSiblingを使うと良いそうです。

// 最前面に移動
GetComponent<RectTransform>().SetAsLastSibling();

// 最背面に移動
GetComponent<RectTransform>().SetAsFirstSibling();

細かく順番を指定したい場合はTransform.GetSiblingIndexTransform.SetAsLastSiblingが使えるようです。

int index = GetComponent<RectTransform>().GetSiblingIndex();
GetComponent<RectTransform>().SetAsLastSibling(index);

リンク

Unity – Scripting API: Transform
https://docs.unity3d.com/ScriptReference/Transform.html