はなちるのマイノート

Unityをメインとした技術ブログ。自分らしくまったりやっていきたいと思いますー!

【Unity】asmdefで"必須パッケージ"と"任意パッケージ"を定義する方法

はじめに

今回はasmdefで必須パッケージと任意パッケージを定義する方法について紹介をしたいと思います。

任意パッケージのサンプル(左)と必須パッケージのサンプル(右)

その前に

AssemblyDefinitionFilesってなんだっけと言う方は一度公式ドキュメント等を参照してみてください。

docs.unity3d.com

また今回利用する知識は以下の3つ。

  • references:アセンブリの参照設定
  • versionDefines:特定のパッケージ(かつ特定バージョン)がある場合にのみシンボル定義を行う
  • defineConstraints:特定のシンボルが定義されているときのみアセンブリを含める

www.hanachiru-blog.com

www.hanachiru-blog.com

やり方

必須パッケージのやり方

referencesdefineConstraintsversionDefinesを利用します。

{
    "name": "Sample1",
    "rootNamespace": "",
    "references": [
        "Unity.Burst"
    ],
    "includePlatforms": [],
    "excludePlatforms": [],
    "allowUnsafeCode": false,
    "overrideReferences": false,
    "precompiledReferences": [],
    "autoReferenced": true,
    "defineConstraints": [
        "ENABLE_BURST"
    ],
    "versionDefines": [
        {
            "name": "com.unity.burst",
            "expression": "",
            "define": "ENABLE_BURST"
        }
    ],
    "noEngineReferences": false
}
必須パッケージの設定

この場合はcom.unity.burstがなければ、asmdefで定義しているアセンブリはコンパイルに含まれないようになります。

任意パッケージのやり方

referencesversionDefinesを利用します。

{
    "name": "Sample1",
    "rootNamespace": "",
    "references": [
        "Unity.Burst"
    ],
    "includePlatforms": [],
    "excludePlatforms": [],
    "allowUnsafeCode": false,
    "overrideReferences": false,
    "precompiledReferences": [],
    "autoReferenced": true,
    "defineConstraints": [],
    "versionDefines": [
        {
            "name": "com.unity.burst",
            "expression": "",
            "define": "ENABLE_BURST"
        }
    ],
    "noEngineReferences": false
}

ここで重要なことはreferencesに含まれているアセンブリ(パッケージ)がなくてもエラーにはならないということですね。

任意パッケージを設定した様子

またコードを書く上で、任意パッケージの利用箇所は#if ~ #endifを用いてコンパイルエラーにならないように書いてあげてください。

// 雑サンプル

#if ENABLE_BURST
using Unity.Burst;
using UnityEngine;

[BurstCompile]
public sealed class BurstDirectCallTest : MonoBehaviour
{
    // 省略
    
    /// <summary>
    /// 32bitのXorShift
    /// </summary>
    [BurstCompile]
    private static uint XorShift(uint value)
    {
        value ^= value << 13;
        value ^= value >> 17;
        value ^= value << 5;
        return value;
    }
}
#endif