LoginSignup
1
2

More than 5 years have passed since last update.

UnityでMenuBarからシーンへのショートカットを作る

Last updated at Posted at 2015-07-09

皆様Unityでシーンを切り替える時、どうされてますでしょうか?

Projectの検索窓でt:sceneとか、直接sceneファイル検索とか...

Editorスクリプトでの対応

SceneOpener.cs
using UnityEditor;

public class SceneOpener{

    [MenuItem("Scenes/Main")]
    private static void OpenMain()
        {
        EditorApplication.OpenScene("Assets/hoge/fuga/Main.unity");
    }
}

こんな感じのEditorスクリプトを書けばショートカットは作成できますが、
如何せん手入力はめんどくさい。

自動化への道

ということで
シーンファイルを検索して、MenuItemを登録するrubyを書いてみました。

sceneregisterer.rb
#!/usr/bin/ruby

#エディタスクリプトのパス
editorpath = "../Assets/hogehoge/SceneOpener.cs"

#クラス宣言文字列
prefix = <<"EOS"
using UnityEditor;
using System;

public class SceneOpener{

EOS

code = prefix

#シーンファイル検索
Dir::glob("../Assets/**/*.unity").each {|f|

  basename = File.basename(f)

  sceneName = basename.sub(".unity","") ;
  scenePath = f.sub("../","");

    code.concat("   [MenuItem(\"SceneOpenerAll/#{sceneName}\")]
        private static void Open#{sceneName}()
        {
           EditorApplication.OpenScene(\"#{scenePath}\");
        }\n")
}

#クラスの括弧
code.concat("\n}")


#ファイルに書き込み
open(editorpath,"r+") {|f|
  f.flock(File::LOCK_EX)
  f.rewind
  f.puts code

  f.truncate(f.tell)
}

これで便利に!

なったのはなったのですが、仕事のProjectでこれを走らせたらテストシーン含め
30個くらい登録されてしまい、結局よく使うシーンを手入力したほうがいいや
という落ちになりました。 ちゃんちゃん

BuilderSettingsの中のシーンだけを取り込む

そもそも重要度の高いSceneしか開く必要ないよねという事で、
BuildSettingsから取り込む方法を考えました。

SceneMenuGenerator.cs
using UnityEngine;
using UnityEditor;
using System.Text;
using System.IO;
using System.Collections;

public class SceneMenu : Editor {

    private static string openerPath = "hogehuga/SceneMenuOpener.cs";

    [MenuItem("Scenes/Generate")]
    private static void Generate()
    {
        string filePath = Application.dataPath + openerPath;

        StreamWriter sr = File.CreateText(filePath);

        sr.WriteLine(
@"
using UnityEditor;
using System.Collections;

public class SceneMenuOpener{");

        foreach (var s in EditorBuildSettings.scenes) {
        //  Debug.LogError(s.path);

            sr.WriteLine(GetMethodStr(s.path));
        }

        sr.WriteLine("}");

        sr.Close();

        AssetDatabase.Refresh();

    }

    private static string GetMethodStr(string scenePath)
    {
        string sceneName = Path.GetFileName(scenePath).Replace(".unity","");

        string baseStr = 
        "[MenuItem(\"Scenes/sceneName\")] " +
        "private static void sceneName() " +
        "{ " +
        "EditorApplication.OpenScene(\"scenePath\"); " +
        "}";

        baseStr = baseStr.Replace("sceneName",sceneName);
        baseStr = baseStr.Replace("scenePath", scenePath);

        return baseStr;
    }

}

これでBuildSettingsの中にあるシーンだけを出せるようになりました。

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