LoginSignup
109
72

More than 5 years have passed since last update.

コマンドラインからUnityのビルドを走らせる。 -基礎編-

Last updated at Posted at 2015-11-20

概要

「Unityのビルドを自動化したい」と思うことありますよね。

え。Cloud Buildがあるから不要…?

まぁそう仰らずに…。

ちょっと長くなるので「基礎編」と「ステップアップ編」に分けて綴っていきます。

手順

残念ながら外からのコマンドだけでは実現できないみたい。
なので、Unityコード側と呼び出し側両方の手順を書いていくよ。

Unity側

ビルド用クラスを作成

Editorフォルダの下に、好きな名前のクラスを用意してね。

BuildClass.cs
using UnityEditor;
using UnityEngine;

public class BuildClass
{
    public static void Build()
    {
        // ビルド対象シーンリスト
        string[] sceneList = {
            "./Assets/scene/title.unity",
            "./Assets/scene/game.unity",
            "./Assets/scene/config.unity"
        };


        // 実行
        string errorMessage = BuildPipeline.BuildPlayer(
                sceneList,                          //!< ビルド対象シーンリスト
                "C:/project/bin/myUnityProj.exe",   //!< 出力先
                BuildTarget.StandaloneWindows,      //!< ビルド対象プラットフォーム
                BuildOptions.Development            //!< ビルドオプション
        );


        // 結果出力
        if( !string.IsNullOrEmpty( errorMessage ) )
            Debug.LogError( "[Error!] " + errorMessage );
        else
            Debug.Log( "[Success!]" );
    }
}

簡潔に仕上げるとこんな感じかな?

解説

大事なのは「クラス名」と「関数名」、それから「BuildPipeline.BuildPlayerの引数」かな。

「クラス名」と「関数名」は好きな名前をつけて良いけど、呼び出し側で使うから、覚えておいてね!

BuildPipeline.BuildPlayer

ビルドを走らせる為の関数だよ。

引数は、

説明
第一 levels string[] ビルドに含めるシーン(.unity)のパスリストだよ。
※プロジェクトフォルダからの相対パスで指定してね。
第二 locationPathName string ビルド成果物の出力先だよ。
※相対パスで指定した場合はプロジェクトフォルダが基点になるよ。
第三 target BuildTarget ビルド対象のプラットフォームを指定してね。
※次回起動時のプラットフォームもこの値に書き換わってしまうので注意が必要だよ。
第四 options BuildOptions ビルドに際してのオプション。
詳しくはリファレンスを見てね。

だよ!

呼び出し側

スクリプト記述

Windows向け

build.bat
"C:\Program Files\Unity\Editor\Unity.exe" -batchmode -quit -logFile .\build.log -projectPath C:\project\myUnityProj -executeMethod BuildClass.Build

Mac向け

build.sh
/Applications/Unity/Unity.app/Contents/MacOS/Unity -batchmode -quit -logFile ./build.log -projectPath ~/project/myUnityProj -executeMethod BuildClass.Build

解説

引数 説明
-batchmode Unityをバックグラウンドで起動するよ。
-quit 処理が終わったら自動で終了するよ。
-logFile ログの出力先を指定してね。
※ログが不要な場合はこのオプションも不要だよ。
-projectPath プロジェクトフォルダのパスを指定してね。
-executeMethod 実行する「クラス名」と「関数名」を指定してね。

とっても簡単ね!

実行

Unity側と呼び出し側の準備が終わったら、Unityを閉じて、呼び出し側のスクリプトを実行してみてね!

BuildPipeline.BuildPlayer に渡した locationPathName の場所に成果物が生成されていたら成功だよ!
※成果物は BuildTarget の指定によって異なるよ。 (StandaloneWindowsなら.exe, Androidなら.apkとか。)

実行中に警告音が鳴ったり、処理が終わっても成果物が生成されていなかったら -logFile で指定したログを見てみてね。
きっと解決のヒントが記載されているよ!

ありがちなのは、

  • (Unity側)levelsのパス指定が間違っている
  • (呼び出し側)-projectPathが間違っている
  • BuildTarget.Androidを指定したけどSDKのパスが指定されていない

とか。



使いこなせればJenkins化とかもできるからきっと便利だよ!
(^o^)/

参考

シリーズ

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