LoginSignup
4
5

More than 5 years have passed since last update.

Unityでタイトルバーの文字列を動的に変更する

Posted at

はじめに

image.png
UnityでWindows用アプリを開発する場合、タイトルバーに表示されるのはPlayerSettingsのProduct Nameになります。
image.png

タイトルバーにバージョン番号などを表示させたい場合は、その都度Product Nameを書き換えることになります。
しかし、UnityのProduct NameはPlayer Prefsの保存先を決める役割を持っているため
バージョンごとに変更していると、Player Prefsに保存されているデータもその都度吹っ飛んでしまいます。
セーブデータをPlayer Prefsに保存しているようなゲームではタイトルバーの文字を気軽に変えられなくなってしまいます。

そこで、Product Nameを変えずにタイトルバーに表示される文字列を変更する方法を紹介します。

ソースコード

いきなりソースコードです

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;

public class TitleBarSample : MonoBehaviour 
{
//Windowsのみに限定
#if UNITY_STANDALONE_WIN
        [DllImport("user32.dll", EntryPoint = "SetWindowText")]
        public static extern bool SetWindowText(System.IntPtr hwnd, System.String lpString);
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        public static extern System.IntPtr FindWindow(System.String className, System.String windowName);
        private void Start()
        {
            //Product NameのWindowを探す
            var windowPtr = FindWindow(null, Application.productName);
            //名前をセットする
            SetWindowText(windowPtr, "newName");
        }
#endif
}

↑のコンポーネントを適当なGameObjectにAddComponentしてビルドすると・・・
image.png
Product Nameを変更することなくタイトルバーを変更することができました。
処理としてはWindowsのAPIを直接叩いてタイトルバーの内容を変更しています。

応用

上の例だと1回しか書き換えていないので、実行中ずっと書き換え出来るようにします。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;

public class TitleBarSetter : MonoBehaviour 
{
    static TitleBarSetter instance = null;

    public static TitleBarSetter Instance { get { return instance;} }

//Windowsのみに限定
#if UNITY_STANDALONE_WIN
    [DllImport("user32.dll", EntryPoint = "SetWindowText")]
    public static extern bool SetWindowText(System.IntPtr hwnd, System.String lpString);
    [DllImport("user32.dll", EntryPoint = "FindWindow")]
    public static extern System.IntPtr FindWindow(System.String className, System.String windowName);

    System.IntPtr hWnd;
    private void Start()
    {
        instance = this;
        DontDestroyOnLoad(this.gameObject);

        //Product NameのWindowを探す
        hWnd = FindWindow(null, Application.productName);
    }
#endif

    public void SetTitleBar(string text)
    {
#if UNITY_STANDALONE_WIN
        SetWindowText(hWnd, text);
#endif
    }
}

↑のコンポーネントを適当なGameObjectにAddComponentして
別のスクリプトからタイトルバーを更新したいタイミングで呼び出します

TitleBarSetter.Instance.SetTitleBar("表示したい文字列");

↓こんな風にFPS表示に使うこともできます。
fps2.gif
他にはゲームの進行状況を表示したり、時刻を表示したり応用がいろいろ効きます。

4
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
4
5