Unity プラットフォーム固有のコンパイル

Unity は、開発者が特定のプラットフォームのビルドにのみ含まれるコードを作成できる、プラットフォーム固有のコンパイル機能を提供します。この機能は、プラットフォーム固有のコードを作成する場合や、特定のプラットフォームに不要なコードを除外してビルドを 最適化 する必要がある場合に役立ちます。

プラットフォーム固有のコンパイルの使用方法

Unity でプラットフォーム固有のコンパイルを使用するには、プリプロセッサ ディレクティブを使用します。プリプロセッサ ディレクティブは、実際のコンパイル プロセスの前に実行されるコンパイラへの特別な命令です。これらのディレクティブを使用すると、ターゲット プラットフォームに基づいて 条件付き コードを含めたり除外したりできます。

Unity でプラットフォーム固有のコンパイルを使用する方法の例を次に示します。

#if UNITY_IOS
    // iOS-specific code
    // This code will only be included in the build for iOS
#elif UNITY_ANDROID
    // Android-specific code
    // This code will only be included in the build for Android
#else
    // Code for other platforms
    // This code will be included in the build for all other platforms
#endif

この例では、'UNITY_IOS' および 'UNITY_ANDROID' ディレクティブが Unity によって提供され、iOS および Android プラットフォーム用のコードを条件付きでコンパイルするために使用できます。 、 それぞれ。'UNITY_EDITOR' (Unity エディター用)、'UNITY_STANDALONE' (スタンドアロン ビルド用)、'UNITY_WEBGL' など、他の利用可能なプラットフォーム固有のディレクティブも使用できます。 (WebGL ビルド用) など。

#if UNITY_EDITOR
    // Editor-specific code
    // This code will only be included when running in the Unity Editor
    using UnityEditor;
#elif UNITY_STANDALONE
    // Standalone build-specific code
    // This code will only be included when building for standalone platforms (Windows, macOS, Linux)
#elif UNITY_WEBGL
    // WebGL-specific code
    // This code will only be included when building for WebGL
    using UnityEngine.Networking;
#endif

// Shared code that will be included in all builds
public class MyScript : MonoBehaviour
{
    private void Start()
    {
#if UNITY_EDITOR
        Debug.Log("Running in Unity Editor");
#elif UNITY_STANDALONE
        Debug.Log("Running in standalone build");
#elif UNITY_WEBGL
        Debug.Log("Running in WebGL build");
#endif
    }
}

結論

プラットフォーム固有のコンパイルを使用することで、開発者は、Unity のさまざまなターゲット プラットフォーム向けにコードベースを整理および最適化したまま、各 プラットフォーム の機能を活用するコードを作成できます。

おすすめの記事
Poppy Playtime からインスピレーションを得て Unity で GrabPack を作成する
Unity でバレットタイムエフェクトを作成する
Unity でインタラクティブなオブジェクトを作成する
Unity でのキネティック インタラクションの実装
Unity で特定のキーを使用して引き出しや食器棚を開ける
Unity のインベントリを使用しないピック アンド ドロップ システム
Unity で車にプレーヤー エントリを追加する