LoginSignup
7
7

More than 5 years have passed since last update.

Unityのアプリ設定ファイルを生成する

Last updated at Posted at 2015-03-16

このイベントに参加したときにEditorでSettingsクラスがあるファイルを書き換えている話を聞いたのでこういう感じなのかなと思って書いてみました。自分は基本的にUnityをほとんど書いたことない人なのであっているかはわかりません。
プロジェクトのディレクトリ構造は下記のような構造です。

ProjectDirectory
ProjectName
|
|-- Assets
    |-- Editor
        |-- SettingsEditor.cs
    |-- Sctipts
        |-- Settings.cs

Editorで表示されるのは、APIHostをpull down menu(Local, Develop, Production)で選び、Createボタンを押すとSettings.csファイルが生成されるようになっています。下記がEditorのコードと設定画面になります。

Editor/SettingsEditor.cs
using UnityEditor;
using UnityEngine;

public class SettingsEditor : EditorWindow
{

    public enum APIHost
    {
        Local,
        Develop,
        Production
    }

    APIHost _host;

    [MenuItem("Window/SettingsEditor")]
    public static void ShowWindow()
    {
        EditorWindow.GetWindow(typeof(SettingsEditor));
    }

    void OnGUI()
    {
        GUILayout.Label ("Host", EditorStyles.boldLabel);
        _host = (APIHost)EditorGUILayout.EnumPopup ("API Host", _host);
        if (GUILayout.Button ("Create")) {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.Directory.GetCurrentDirectory() + "/Assets/Scripts/Settings.cs"))
            {
                var host = "";
                switch (_host)
                {
                case APIHost.Local:
                    host = "http://127.0.0.1:8000";
                    break;
                case APIHost.Develop:
                    host = "http://develop.com";
                    break;
                case APIHost.Production:
                    host = "http://production.com";
                    break;
                }

                file.WriteLine ("using System;");
                file.WriteLine ("using System.Collections;");
                file.WriteLine ("using System.Collections.Generic;");
                file.WriteLine ("using UnityEngine;");
                file.WriteLine ("");
                file.WriteLine ("public static class Settings");
                file.WriteLine ("{");
                file.WriteLine (string.Format("    public static string Host = \"{0}\";", host));
                file.WriteLine ("}");
        }
        }
    }
}

Settings GUI

Createボタンを押すと下記のような中身のコードが生成され、設定値が変わるようになっています。

Scripts/Settings.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class Settings

{
    public static string Host = "http://develop.com";
}

このようにやればいちいちコード上で書き換えたりせず、GUIの設定画面で設定を楽に書き換えられたりすると思います。

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