Build and run unity iphone

Building for iOS

Cloud Build helps you automate the process of building your Unity Project for iOS Apple’s mobile operating system. More info
See in Glossary devices.

This article describes the prerequisites necessary to build your Project for iOS and create the supporting components to configure Cloud Build A continuous integration service for Unity projects that automates the process of creating builds on Unity’s servers. More info
See in Glossary . Topics covered include:

  • Joining the Apple Developer Program
  • Creating an iOS certificate and p12 file
  • Adding devices to your profile
  • Creating a provisioning profile
  • Configuring your app to build for iOS

Joining the Apple Developer Program

To develop iOS apps, you must be a member of the Apple Developer Program. This lets you build, test, and eventually release your apps in the Apple App Store.

Note: You must have an Intel-based Mac running OS X Yosemite (v10.10) or later to develop and distribute iOS apps and Mac apps.

After you sign in to the Apple Developer program portal, you’ll see a list labeled Program Resources on the left. Click Certificates, IDs & Profiles to manage the certificates, identifiers, profiles, and devices you need to develop and distribute apps.

Provisioning profiles

A provisioning profile ties developers and devices to an authorized Development Team and enables you to use a device for testing. You must install a Development Provisioning Profile on each device you plan to run your application code.

Each Development Provisioning Profile contains a set of Development Certificates, Unique Device Identifiers (UDID), and an App ID.

To use a device for testing, you must also include your Development Certificate in the profile. A single device can contain multiple provisioning profiles.

Components of a provisioning profile

Certificates determine whether your app is development-only or a release candidate for the App Store. You should use an Ad Hoc Production Certificate so that you can test all the features of your game (such as GameCenter).

Identifiers are the unique IDs that identify your project. For basic projects, or if this is your first iOS project, you should make an App ID. This is often the same as your Unity3D Project’s Bundle ID.

Tip: For more information on signing identities and certificates, see Maintaining Your Signing Identities and Certificates on the Apple developer website.

Devices are the hardware—such as an iPhone, iPad, or iPod—on which you plan to test your project. You must retrieve the UDID for each device on which you plan to test your game. You then add the UDID to the Devices section in the iOS developer portal.

Note: Each year, you can register a fixed number of devices. The maximum number of devices you can register is 100 devices per product family per membership year. For more information see, Registering Devices Using Your Developer Account in the Maintaining Identifiers, Devices, and Profiles topic on the Apple developer website.

Creating an iOS certificate and p12 file

When you create a certificate, you must decide whether to create a Development Certificate (used only for testing), or a Production Certificate, which you use to distribute your app via the App Store.

Tip: Create a Production Certificate. While either certificate type works for development, Production Certificates make it easier to release your app to the App Store.

Create a certificate

  1. Sign in to your Apple Developer Program.
  2. Click Member Center >Certificates >Identifiers & Profiles >Certificates.
  3. In the left-hand column, under Certificates, click All.
  4. In the screen labeled What type of certificate do you need, choose the type of certificate to generate. Typically, if you’re starting, you should to pick an App Store and Ad Hoc production certificate.
  5. Use the Keychain Access program on your Mac (open your Finder and find it in Applications/Utilities) to generate a Certificate Signing Request (CSR) file. Follow the instructions in the iOS portal to complete this step. Make a note of where you save the CSR file.
  6. In the Generate your certificate screen, upload your CSR file (which might have the extension .certSigningRequest). Click the Choose File button and select your CSR file, and then click the Generate button.
  7. To download your certificate to your Mac, click the Download button on the Your Certificate is Ready screen. Store this file somewhere safe and back it up.
Читайте также:  Где поменять имя iphone

To add the certificate to a keychain, locate the certificate file and double-click it. This opens the Keychain Access program. If you get a popup with the message “Do you want to add the certificate to a keychain?”, choose login and click the Add button.

Export a p12 file

To create apps using Unity Cloud Build, you must convert your certificate file to a p12 file. A p12 file is a file that contains your private key and certificate and is used to sign your code. Typically, if you develop a project in native Xcode, this process is handled behind the scenes A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary .

To generate a p12 file:

On your Mac, open up your Finder and in Applications/Utilities, open the Keychain Access program.

In the left-hand column, under keychains, verify that Login is selected.

In the left-hand column, under Category, verify that My Certificates is selected. In the main Keychain Access pane, select your certificate.

Note: Typically, your certificate is located under My Certificates. If it is not there, check under Certificates.

From the File menu, select File > Export Items, or right-click and select Export.

Select Personal Information Exchange (.p12) from the File Format drop-down menu.

Note: If Login under Keychains and My Certificates under Category is not selected, the p12 option is greyed out.

Ceate a password for the p12 file.

Note: Record the password somewhere safe as you must supply it when setting up iOS builds on Unity Cloud Build.

Adding devices

For development purposes, Apple requires the UDID for each device on which you intend to install your app. Once your app is accepted into the App Store, anyone can download and install it; provided they have the correct version of iOS and meet any other requirements.

Finding your UDIDs

You can use iTunes to retrieve the UDID of your device. For a walkthrough of the retrieval process, see WhatsMyUDID.com.

The basic steps are:

  1. Open iTunes on your Mac.
  2. Connect the device (iPhone, iPad, etc) to the computer.
  3. In iTunes, select the device.
  4. You should see a screen with the device name, capacity, and other details about the device. To display the UDID, click the Serial # field.
  5. Copy and paste the UDID into a document where you can retrieve it later.
  6. Close iTunes and disconnect your device.

Add the UDID in the Apple developer portal

To add your device UDID(s) to the Apple Developer Portal:

  1. Click the All section under Devices in the left column of the Apple Developer Portal.
  2. To add a new UDID, click the Add button (+) in the upper-right corner
  3. Give the device a name you will recognize, and copy-paste the UDID you got from iTunes into the UDID field.
  4. Click Continue.

Repeat the steps for each of your devices.

Create App ID

Now that you’ve created your iOS Certificate, you can create an App ID:

In the left-hand column of the Apple Developer Portal, click App ID.

In the Register iOS App IDs pane, at the top right, click the Add button (+).

  • In the Registering an App ID pane, enter the following information:
    1. App ID Description: The name of your app, without any special characters.
    2. App ID Suffix: If you intend to incorporate specific services such as Game Center or In-App Purchases, create an Explicit ID. If you don’t need these services, then create a Wildcard App ID. A Wildcard App ID lets you re-use the App ID for multiple projects.
    3. App Services: Optional. Indicate whether you plan to use any of the Apple App Services.

    For more information on registering an App ID, see Maintaining Identifiers, Devices, and Profiles.

    Click the Continue button.

    Читайте также:  Iphone x процессор a11 bionic

    On the Confirm your App ID page, check the information you’ve provided and then click the Submit button.

    Create a provisioning profile

    The next step is to generate a .mobileprovision file. The .mobileprovision file combines your p12 certificate, App ID, and identifies the UDIDs of the devices on which you are testing your app.

    1. In the Apple Developer portal, click Certificates, IDs & Profiles.
    2. In the left-hand column of the Apple Developer Portal, under Provisioning Profiles, select All.
    3. To add a new Provisioning Profile, click the Add button (+) in the upper-right corner.
    4. Under Development, select the type of provisioning profile to create and click Continue. Note: If you’re just getting started, you should use a Distribution >Ad Hoc certificate, as this lets you build your game and test it on devices.
    5. Select the App ID to use for development, and click the Continue button.
    6. Select one or more development certificates, and click the Continue button.
    7. Select one or more devices, and click the Continue button.
    8. Enter a profile name, and click the Generate button.
    9. Click Done.

    Download the generated .mobileprovision file to your desktop machine.

    Configuring your app to build for iOS

    To configure your iOS Cloud Build, you need the following items:

    • Your provisioning profile (.mobileprovision)
    • Your .p12 file
    • The password for your .p12 file

    For basic iOS usage this process should be sufficient. For projects that include Xcode frameworks, you must perform some additional configuration.

    Using Xcode Frameworks

    To add Xcode frameworks manually, use the Xcode Manipulation API. The API lets you manage external Xcode frameworks.

    For an example of a Unity Project that uses the API, see the UpdateXcodeProject example Project on BitBucket. You can use the example to experiment and to learn from.

    One of the plugins of the example Project is an external Xcode project manipulation DLL. The DLL is the build product of the source available in Unity’s Bitbucket repository. A preferred way to include Xcode project manipulation functionality is to copy the C# source code files to the Assets/Editor folder in your Project.

    You can use the Xcode Manipulation API in the following ways:

    • Use the built-in Unity PostProcessBuildAttribute, which is executed before the Unity Cloud Build Post-Export method runs.
    • Use the Unity Cloud Build Post-Export method (requires access to advanced settings).

    Источник

    Запуск игры на Unity из приложения SwiftUI для iOS

    С версии 2019.3 Unity поддерживает загрузку и выгрузку игры на Unity из нативного приложения для iOS или Android с помощью функции «Unity as a Library». Это удобный способ встроить игру в нативное мобильное приложение и отделить логику игры от логики iOS-приложения.

    Unity дает инструменты, которые позволяют управлять загрузкой, активацией и выгрузкой библиотеки среды выполнения в нативном приложении. В остальном процесс сборки мобильного приложения остается в основном неизменным. Unity позволяет создавать проекты для Xcode (iOS) и Gradle (Android).

    Однако сам процесс встраивания может быть довольно сложным, особенно если нужно интегрировать игру на Unity в приложение SwiftUI. Но не волнуйтесь: именно с этим вопросом мы сейчас и разберемся!

    Итак, засучим рукава и приступим к делу! ?

    Создание iOS-проекта

    В первую очередь нужно создать пустой iOS-проект в рабочей области. Проще всего это сделать так: создайте пустой проект в XCode, а затем выберите пункт меню File → Save As Workspace. Назовем проект и рабочую область SwiftyUnity.

    Примечание.

    В качестве интерфейса выберите Storyboard, для жизненного цикла проекта укажите UIKit App Delegate. Не волнуйтесь: позже мы сделаем из этого приложение SwiftUI — эти этапы нужны лишь для того, чтобы работала интеграция Unity.

    Кроме того, поскольку это будет проект SwiftUI, не забудьте для минимальной цели развертывания iOS указать 13.0.0.

    Создание проекта Unity

    Далее нужно создать пустой проект Unity. Где он будет находиться, неважно, но лучше всего — в папке с нашей рабочей областью и iOS-проектом. Назовем наш проект UnityGame.

    Единственная функциональность, которую мы добавим в сцену Unity по умолчанию, — кнопка, которая закрывает игру и возвращает пользователя в приложение iOS. Добавьте игровой объект «кнопка» в сцену Unity и задайте для нее текст «Quit Game».

    Теперь добавим кнопке сценарий QuitBehavior.cs — он очень простой, поскольку единственное, что нам нужно, это выгрузить игру на Unity и вернуться в приложение для iOS.

    Нам нужно подключить к кнопке прослушиватель OnButtonPressed. Не забывайте: чтобы функция отображалась в списке, ее нужно пометить как public в прикрепленном сценарии.

    Читайте также:  The apple name story

    Этой игровой функциональности пока что будет достаточно, поскольку наша цель — загрузить и выгрузить игру из приложения iOS. Теперь пора собрать игру на Unity как iOS-проект.

    В проекте Unity откройте настройки сборки: File → Build Settings. Здесь нужно изменить платформу с PC, Mac & Linux Standalone на iOS, нажать кнопку Switch Platform и немного подождать, пока Unity перекомпилируется.

    Следующий шаг — экспортировать проект Unity как iOS-проект. Настройки менять не нужно — просто нажмите Build. Проект Unity мы экспортируем в папку с именем UnityExport.

    Теперь в корневой папке рабочей области у нас должно быть три каталога:

    SwiftyUnity — основное приложение для iOS.

    UnityGame — проект игры на Unity.

    UnityExport — экспорт игры в виде iOS-проекта.

    Если у вас папки расположены не так — ничего страшного: если правильно подключить проекты (что мы сделаем на следующем этапе), всё будет работать.

    Подключение Unity к iOS

    Теперь подключим экспортированный проект Unity к приложению SwiftUI. Откройте рабочую область SwiftyUnity.xcworkspace, в которой пока что только проект «SwiftyUnity».

    В приложении Finder найдите проект «UnityExport» и перетащите файл Unity-iPhone.xcodeproj в рабочую область.

    Теперь SwiftyUnity.xcodeproj и Unity-iPhone.xcodeproj принадлежат одной рабочей области. Если после перетаскивания Unity-iPhone.xcodeproj отображается красным, проверьте, установлено ли в правой панели проекта для Location значение Relative to Workspace.

    Затем щелкните проект «SwiftyUnity» и выберите цель «SwiftyUnity». В меню General прокрутите вниз до раздела Frameworks, Libraries and Embedded Content. Добавьте новый фреймворк, щелкнув кнопку +.

    Выберите из списка UnityFramework.framework и добавьте его в проект.

    Затем выберите папку Data в проекте «Unity-iPhone» и на правой панели в разделе Target Membership отметьте UnityFramework.

    После этого откройте Info.plist и удалите запись Application Scene Manifest — приложение «сломается», но мы разберемся с этим позже в файле «AppDelegate».

    С конфигурацией пока что всё — пришло время писать код!

    Щепотка кода

    Для начала создадим представление SwiftUI с именем ContentView.swift — это будет точка входа в SwiftUI — и добавим кнопку, которая запускает игру. Прослушиватель кнопки оставим пустым — мы вернемся сюда, как только напишем код, запускающий игру на Unity.

    Мы изначально создали приложение UIKit Storyboard (а не приложение SwiftUI), поэтому теперь нужно подключить наш ContentView к сгенерированному корневому ViewController. Так что следующий этап — обновить код ViewController.swift:

    Самое важное, конечно же, — это реализация связи приложения с игрой через импортированный ранее UnityFramework. Познакомиться с этим фреймворком подробнее можно на странице официальной документации.

    Мы создадим вспомогательный одноэлементный класс с именем Unity, который можно использовать для всего, что связано с UnityFramework. Создайте новый класс со следующим кодом:

    Настроим «AppDelegate», чтобы можно было запустить приложение. Откройте AppDelegate.swift и удалите все функции, связанные со сценой. Также нам понадобится передать в Unity ссылку на главное окно приложения — поскольку мы будем возвращаться в него после выгрузки игры.

    После этих изменений «AppDelegate» должен выглядеть так:

    И теперь осталось только запустить игру из нашего ContentView.

    Для этого достаточно просто вызвать метод show() из класса Unity внутри прослушивателя кнопки — вот так:

    Вот и всё. Давайте запустим приложение и проверим его работу!

    Внимание: запускайте приложение на физическом устройстве iPhone — не в симуляторе.

    На гифке показано, как должен выглядеть окончательный результат:

    Вуаля! Теперь мы можем загрузить игру на Unity из нативного приложения SwiftUI и вернуться в него, нажав кнопку «Quit Game». Можете себя похвалить — вы это заслужили!

    Что дальше?

    Загрузка и выгрузка Unity — это только начало. Часто приходится передавать данные из нативного приложения в игру на Unity и наоборот: например, передать в игру перед ее запуском данные об игроке или отправить результаты игры в нативное приложение iOS, чтобы оно могло их отформатировать и отправить на сервер.

    Можно даже использовать собственный контроллер для игры через Bluetooth, который будет управляться из нативной части и передаваться в Unity! Возможности здесь безграничны — к тому же, всегда удобно держать нативную логику отдельно от игровой.

    И UnityFramework предоставляет такую функциональность: с его помощью можно обмениваться данными с Unity. Если вам это интересно — следите за обновлениями: в следующей статье я расскажу о взаимодействии между iOS и Unity! ?

    О переводчике

    Перевод статьи выполнен в Alconost.

    Alconost занимается локализацией игр, приложений и сайтов на 70 языков. Переводчики-носители языка, лингвистическое тестирование, облачная платформа с API, непрерывная локализация, менеджеры проектов 24/7, любые форматы строковых ресурсов.

    Мы также делаем рекламные и обучающие видеоролики — для сайтов, продающие, имиджевые, рекламные, обучающие, тизеры, эксплейнеры, трейлеры для Google Play и App Store.

    Источник

  • Оцените статью