Version: Unity 6.0 (6000.0)
言語 : 日本語
Package management with the scripting API
パッケージアセットへのアクセス

パッケージ用のスクリプティング API

Package Manager のスクリプティング API を使用して、C# スクリプトを通して Package Manager を操作できます。例えば、ターゲットマシンのプラットフォームに応じて、特定のパッケージやバージョンをインストールしたい場合などです。

システムは、PackageManager.Client クラスに大きく依存しています。これを使うと、パッケージの検索、パッケージのリストの参照、スクリプトによるパッケージのインストールとアンインストールをスクリプト経由で行えます。

もう 1 つの重要なクラスは PackageManager.PackageInfo です。このクラスには、パッケージマニフェストやレジストリから取得したメタデータなど、パッケージの状態が含まれます。例えば、パッケージで使用可能なバージョンのリストや、パッケージの検索またはインストール中に発生する可能性のあるエラーのリストを取得できます。

プロジェクトにパッケージを追加

この例では、Client クラスを使用してプロジェクトにパッケージをインストールまたは加える方法を示しています。

Client.Add を使用してパッケージを追加できます。Client.Add メソッドを呼び出すときは、パッケージ名だけ、または特定のバージョンの名前を指定できます。例えば、Client.Add("com.unity.textmeshpro") を使用すると、最新バージョンの TextMesh Pro パッケージがインストール (またはそのパッケージにアップデート) され、Client.Add("com.unity.textmeshpro@1.3.0") を使用すると、バージョン 1.3.0 の TextMesh Pro パッケージがインストールされます。

Client.Add メソッドは AddRequest インスタンスを返します。これを使用して、新しく追加されたパッケージの状態、エラー、または PackageInfo 情報を含むリクエスト反応を取得できます。

using System;
using UnityEditor;
using UnityEditor.PackageManager.Requests;
using UnityEditor.PackageManager;
using UnityEngine;

namespace Unity.Editor.Example {
   static class AddPackageExample
   {
       static AddRequest Request;

       [MenuItem("Window/Add Package Example")]
       static void Add()
       {
           // Add a package to the project
           Request = Client.Add("com.unity.textmeshpro");
           EditorApplication.update += Progress;
       }

       static void Progress()
       {
           if (Request.IsCompleted)
           {
               if (Request.Status == StatusCode.Success)
                   Debug.Log("Installed: " + Request.Result.packageId);
               else if (Request.Status >= StatusCode.Failure)
                   Debug.Log(Request.Error.message);

               EditorApplication.update -= Progress;
           }
       }
   }
}

プロジェクト内のパッケージのリストを参照

この例は、Client クラスを使用してプロジェクト内のパッケージを繰り返し使用する方法を示しています。

Client.List メソッドは ListRequest インスタンスを返します。このインスタンスを使用して、リスト操作の状態、エラー、または繰り返し可能な PackageCollection を含むリクエスト反応を取得できます。

using System;
using UnityEditor;
using UnityEditor.PackageManager.Requests;
using UnityEditor.PackageManager;
using UnityEngine;

namespace Unity.Editor.Example {
   static class ListPackageExample
   {
       static ListRequest Request;

       [MenuItem("Window/List Package Example")]
       static void List()
       {
           Request = Client.List();    // List packages installed for the project
           EditorApplication.update += Progress;
       }

       static void Progress()
       {
           if (Request.IsCompleted)
           {
               if (Request.Status == StatusCode.Success)
                   foreach (var package in Request.Result)
                       Debug.Log("Package name: " + package.name);
               else if (Request.Status >= StatusCode.Failure)
                   Debug.Log(Request.Error.message);

               EditorApplication.update -= Progress;
           }
       }
   }
}

プロジェクトにパッケージを埋め込む

この例は、Client クラスを使用して、すでにプロジェクトにインストールされているパッケージの 1 つを埋め込む方法を示しています。メインメソッドである Client.Embed は、パッケージのコピーを作成し、プロジェクトの Packages フォルダーに格納します。

Client.Embed メソッドは EmbedRequest インスタンスを返します。このインスタンスを使用して、埋め込み操作の状態、エラー、または新しく埋め込まれたパッケージの PackageInfo 情報を含むリクエスト反応を取得できます。

以下の例でも Client.List メソッドを使用し、現在プロジェクトにインストールされているパッケージの集合にアクセスし、埋め込みでもビルトインでもない最初のパッケージを選択します。

Client.List メソッドは ListRequest インスタンスを返します。このインスタンスを使用して、リスト操作の状態、エラー、または繰り返し可能な PackageCollection を含むリクエスト反応を取得できます。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.PackageManager.Requests;
using UnityEditor.PackageManager;
using UnityEngine;

namespace Unity.Editor.Example
{
    static class EmbedPackageExample
    {
        static String targetPackage;
        static EmbedRequest Request;
        static ListRequest LRequest;

        [MenuItem("Window/Embed Package Example")]
        static void GetPackageName()
        {
            // First get the name of an installed package
            LRequest = Client.List();
            EditorApplication.update += LProgress;
        }

        static void LProgress()
        {
            if (LRequest.IsCompleted)
            {
                if (LRequest.Status == StatusCode.Success)
                {
                    foreach (var package in LRequest.Result)
                    {
                        // Only retrieve packages that are currently installed in the
                        // project (and are neither Built-In nor already Embedded)
                        if (package.isDirectDependency && package.source
                            != PackageSource.BuiltIn && package.source
                            != PackageSource.Embedded)
                        {
                            targetPackage = package.name;
                            break;
                        }
                    }

                }
                else
                    Debug.Log(LRequest.Error.message);

                EditorApplication.update -= LProgress;

                Embed(targetPackage);

            }
        }

        static void Embed(string inTarget)
        {
            // Embed a package in the project
            Debug.Log("Embed('" + inTarget + "') called");
            Request = Client.Embed(inTarget);
            EditorApplication.update += Progress;

        }

        static void Progress()
        {
            if (Request.IsCompleted)
            {
                if (Request.Status == StatusCode.Success)
                    Debug.Log("Embedded: " + Request.Result.packageId);
                else if (Request.Status >= StatusCode.Failure)
                    Debug.Log(Request.Error.message);

                EditorApplication.update -= Progress;
            }
        }
    }
}


Package Manager イベント

Events クラスを使用して、Package Manager にイベントハンドラーを登録します。Events クラスには、サブスクライブできる 2 つのイベントが含まれています。Package Manager は次のタイミングでイベントを発生させます。

  • Package Manager が依存関係のリストを変更する直前 (registeringPackages)
  • Package Manager がパッケージの依存関係の変更されたリストをインポートしてコンパイルした後 (registeredPackages)

以下の例では、これらのイベントの使用方法を示しています。

RegisterPackages イベントの使用例

using UnityEditor.PackageManager;
using UnityEngine;

namespace Unity.Editor.Example
{
    public class EventSubscribingExample_RegisteringPackages
    {
        public EventSubscribingExample_RegisteringPackages()
        {
            // Subscribe to the event using the addition assignment operator (+=).
            // This executes the code in the handler whenever the event is fired.
            Events.registeringPackages += RegisteringPackagesEventHandler;
        }

        // The method is expected to receive a PackageRegistrationEventArgs event argument.
        void RegisteringPackagesEventHandler(PackageRegistrationEventArgs packageRegistrationEventArgs)
        {
            Debug.Log("The list of registered packages is about to change!");

           foreach (var addedPackage in packageRegistrationEventArgs.added)
            {
                Debug.Log($"Adding {addedPackage.displayName}");
            }

            foreach (var removedPackage in packageRegistrationEventArgs.removed)
            {
                Debug.Log($"Removing {removedPackage.displayName}");
            }

            // The changedFrom and changedTo collections contain the packages that are about to be updated.
            // Both collections are guaranteed to be the same size with indices matching the same package name.
            for (int i = 0; i <= packageRegistrationEventArgs.changedFrom.Count; i++)
            {
                var oldPackage = packageRegistrationEventArgs.changedFrom[i];
                var newPackage = packageRegistrationEventArgs.changedTo[i];

                Debug.Log($"Changing ${oldPackage.displayName} version from ${oldPackage.version} to ${newPackage.version}");
            }
        }
    }
}

registeredPackages イベントの使用例

using UnityEditor;
using UnityEditor.PackageManager;
using UnityEngine;

namespace Unity.Editor.Example
{
    public class EventSubscribingExample_RegisteredPackages
    {
        // You must use '[InitializeOnLoadMethod]' or '[InitializeOnLoad]' to subscribe to this event.
        [InitializeOnLoadMethod]
        static void SubscribeToEvent()
        {
            // This causes the method to be invoked after the Editor registers the new list of packages.
            Events.registeredPackages += RegisteredPackagesEventHandler;
        }

        static void RegisteredPackagesEventHandler(PackageRegistrationEventArgs packageRegistrationEventArgs)
        {
            // Code executed here can safely assume that the Editor has finished compiling the new list of packages
            Debug.Log("The list of registered packages has changed!");
        }
    }
}
Package management with the scripting API
パッケージアセットへのアクセス