コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】Build Settings の設定(BuildPlayerOptions)をスクリプトから取得する方法

概要

using UnityEditor;

public static class Example
{
    [MenuItem( "Tools/Hoge" )]
    public static void Hoge()
    {
        var defaultBuildPlayerOptions = new BuildPlayerOptions();

        var options = BuildPlayerWindow.DefaultBuildMethods
            .GetBuildPlayerOptions( defaultBuildPlayerOptions );

        BuildPipeline.BuildPlayer( options );
    }
}

BuildPlayerWindow.DefaultBuildMethods.GetBuildPlayerOptions を使用すれば

f:id:baba_s:20220128172636p:plain

Build Settings の設定(BuildPlayerOptions)を取得できるが

f:id:baba_s:20220128172724p:plain

ビルドの出力先を選択するダイアログが表示されてしまうので

using System.Reflection;
using UnityEditor;

public static class BuildPlayerWindowDefaultBuildMethodsInternal
{
    public static BuildPlayerOptions GetBuildPlayerOptionsInternal
    (
        bool               askForLocation,
        BuildPlayerOptions defaultOptions
    )
    {
        var type        = typeof( BuildPlayerWindow.DefaultBuildMethods );
        var bindingAttr = BindingFlags.NonPublic | BindingFlags.Static;
        var methodInfo  = type.GetMethod( "GetBuildPlayerOptionsInternal", bindingAttr );
        var parameters  = new object[] { askForLocation, defaultOptions };

        return ( BuildPlayerOptions ) methodInfo.Invoke( null, parameters );
    }
}

上記のようなクラスを定義して

using System.IO;
using UnityEditor;

public static class Example
{
    [MenuItem( "Tools/Hoge" )]
    public static void Hoge()
    {
        var defaultBuildPlayerOptions = new BuildPlayerOptions();

        // ビルドの出力先を絶対パスで指定
        // 絶対パスで指定しないと以下のエラーが出てビルドに失敗してしまう
        // UnityException: Build path contains project built with
        // "Create Visual Studio Solution" option,
        // which is incompatible with current build settings.
        // Consider building your project into an empty directory.
        var location = Path.GetFullPath( "Game/Game.exe" );

        EditorUserBuildSettings.SetBuildLocation
        (
            target: EditorUserBuildSettings.activeBuildTarget,
            location: location
        );

        // ビルドの出力先を選択するダイアログを表示せずに
        // Build Settings の設定(BuildPlayerOptions)を取得
        var options = BuildPlayerWindowDefaultBuildMethodsInternal
            .GetBuildPlayerOptionsInternal( false, defaultBuildPlayerOptions );

        // ゲームをビルド
        BuildPipeline.BuildPlayer( options );
    }
}

このようなコードを書くことで Build Settings の設定を使用して
独自のビルドフローを実装できる

参考サイト様