Version: 2019.2
Сборка плагина для iOS
Customising WWW requests on iOS

Preparing your application for In-App Purchases (IAP)

Эта глава не описывает, как интегрировать вашу игру с StoreKit API от Apple. Предполагается, что у вас уже есть интеграция с StoreKit через плагин нативного кода.

The Apple StoreKit documentation defines four kinds of products that can be sold via the In-App Purchase process:

  • Контент
  • Функционал
  • Услуги
  • Подписки

Эта глава покрывает только первый случай, и, по большей части, концентрируется на концепте скачиваемого контента (downloadable content - DLC). Для реализации DLC в Unity рекомендуются AssetBundles. В данном разделе будет рассказано про создание и использование AssetBundles.

Экспорт ваших ассетов для использования на iOS

Иногда бывает полезным поддерживать раздельные проекты для вашего главного приложения и скачиваемых AssetBundles, которые оно использует. Однако вам следует учесть, что все скрипты на которые ссылаются объекты в AssetBundle должны находиться в исполнительном файле главного проекта. У проекта, который вы используете для создания AssetBundle, в качестве цели сборки должен быть выбран iOS, т.к. содержимое AssetBundle файлов не совместимо между iOS и другими платформами.

AssetBundles are created using editor scripts - a simple example is given below:

using UnityEngine;
using UnityEditor;

public class ExportBundle : MonoBehaviour {
    [MenuItem ("Assets/Build AssetBundle From Selection - Track dependencies")]
    static void DoExport() {
        string str = EditorUtility.SaveFilePanel("Save Bundle...", Application.dataPath, Selection.activeObject.name, "assetbundle");
        if (str.Length != 0) {
            BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, str, BuildAssetBundleOptions.CompleteAssets, BuildTarget.iPhone);
        }
    }
}

You should save this code in a file called ExportBundle and place it inside a folder called Editor (you can just create this if it isn’t already present in the project). The script will add a menu item entitled Build AssetBundle From Selection - Track dependencies on the Assets menu in the editor.

The content you want to include in the bundle should be prepared in the form of prefabs. Select a prefab in the Project view and then select Assets > Build AssetBundle From Selection - Track dependencies (i.e. the menu item added by the ExportBundle script). This command will bring up a save dialog where you can choose the name and location of your AssetBundle file.

Загрузка ваших ассетов на iOS

Note: Apple may change the folder locations where you are permitted to write data. Always check the latest Apple documentation to be sure your application will be compliant. The following advice was correct as of early 2018.

AssetBundles can be downloaded using the WWW class and once transfer is complete, the enclosed assets can be accessed. The recommended way to download an AssetBundle is to use LoadFromCacheOrDownload as shown in the following sample:

IEnumerator GetAssetBundle() {
    WWW download;
    string url = "http://somehost/somepath/someassetbundle.assetbundle";

    while (!Caching.ready)
        yield return null;

    download = WWW.LoadFromCacheOrDownload(url, 0);

    yield return download;

    AssetBundle assetBundle = download.assetBundle;
    if (assetBundle != null) {
        // Alternatively you can also load an asset by name (assetBundle.Load("my asset name"))
        Object go = assetBundle.mainAsset;
            
        if (go != null)
            Instantiate(go);
        else
            Debug.Log("Couldn't load resource");    
    } else {
        Debug.Log("Couldn't load resource");    
    }
}

The downloaded asset bundle files are stored in the Library folder of the iOS application sandbox and have the No Backup flag set on them. This means the OS won’t delete these files accidentally and these files won’t be backed up to iCloud.

If you need to choose exactly where the AssetBundle file is stored, you can use a standard WWW download (i.e. just use the constructor instead of LoadFromCacheOrDownload) and then save the downloaded data on disk using the .NET file API. You can save required files to the Application.temporaryCachePath folder (stored in Library/Caches which is regularly “cleaned out” by the OS) or the Application.persistentDataPath folder (stored in Documents which is not cleaned out by the OS). You should set the No Backup flag on these files with iOS.Device.SetNoBackupFlag to prevent them being backed up to iCloud.

На заметку: Если вы не поставите флажок No Backup, то ваше приложение может быть отклонено при его подаче в App Store.

Вы можете получить доступ к сохранённым файлам, создав WWW объект к URL в форме file:///pathtoyourapplication/Library/savedassetbundle.assetbundle:-

string cachedAssetBundle = Application.temporaryCachePath + "/savedassetbundle.assetbundle"; 
System.IO.FileStream cache = new System.IO.FileStream(cachedAssetBundle, System.IO.FileMode.Create);
cache.Write(download.bytes, 0, download.bytes.Length);
cache.Close();

iOS.Device.SetNoBackupFlag(cachedAssetBundle);

Debug.Log("Cache saved: " + cachedAssetBundle);

Note: You can test the reading of stored files in the Documents folder if you enable file sharing (setting UIFileSharingEnabled to true in your Info.plist allows you to access the Documents folder from iTunes). Note that the contents of the Documents folder are cached to iCloud, so you should not use this location to store AssetBundles in the final build to be shipped. See File System Basics in the Apple iOS documentation for further details.


  • 2018–06–14 Page amended
Сборка плагина для iOS
Customising WWW requests on iOS
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961