LoginSignup
15
14

More than 5 years have passed since last update.

uGUIのパーツを一発生成

Posted at

FacebookのUnity助け合い所でこんな質問投げさせてもらいました。

Unityユーザー助け合い所.png

これがですね、何をしたかったかというと、デバックモード用のUIを作りたかったんですよね。
必要な分だけコードで生成みたいな。

結果から言うと整備されていなさそうなので、
時間もないので、見つけたリンクのフォーラムの内容を参考に、
自己ソリューションしてみました。

一部RenderModeの改修があったようで直しました。

uGUITest.cs
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class uGUITest : MonoBehaviour
{
    private void Start()
    {
        if (FindObjectOfType<EventSystem>() == null)
        {
            var es = new GameObject("EventSystem", typeof(EventSystem));
            es.AddComponent<StandaloneInputModule>();
        }

        var canvasObject = new GameObject("Canvas");
        var canvas = canvasObject.AddComponent<Canvas>();
        canvasObject.AddComponent<GraphicRaycaster>();
        canvas.renderMode = RenderMode.ScreenSpaceOverlay;

        var buttonObject = new GameObject("Button");
        var image = buttonObject.AddComponent<Image>();
        image.transform.parent = canvas.transform;
        image.rectTransform.sizeDelta = new Vector2(180, 50);
        image.rectTransform.anchoredPosition = Vector3.zero;
        image.color = new Color(1f, .3f, .3f, .5f);

        var button = buttonObject.AddComponent<Button>();
        button.targetGraphic = image;
        button.onClick.AddListener(() => Debug.Log(Time.time));

        var textObject = new GameObject("Text");
        textObject.transform.parent = buttonObject.transform;
        var text = textObject.AddComponent<Text>();
        text.rectTransform.sizeDelta = Vector2.zero;
        text.rectTransform.anchorMin = Vector2.zero;
        text.rectTransform.anchorMax = Vector2.one;
        text.rectTransform.anchoredPosition = new Vector2(.5f, .5f);
        text.text = "Yo 世界!";
        text.font = Resources.FindObjectsOfTypeAll<Font>()[0];
        text.fontSize = 20;
        text.color = Color.yellow;
        text.alignment = TextAnchor.MiddleCenter;
    }
}

このコードを空のオブジェクトにつけると、
ボタンが一つ生成される仕組みになっています。

これを再生すると、
Untitled_-_OclusProject_-_PC__Mac___Linux_Standalone.png

このようになります。
これが便利だなーって思ったのが、EventSystemがなかったら作ってね!って最初に入っているのがまだ使い慣れていない自分としては良いなと思いました。

…と、ここまで書いたところで、本来uGUIはこうゆう使い方するものじゃないのかなーなんて思い、デバック用のUIは引き続きOnGUIなんだなーって目が覚めました(笑)

うむ。

15
14
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
15
14