Unity apps

How to build Unity mobile apps with codemagic.yaml

Unity is a cross-platform game engine developed by Unity Technologies. It can be used to create mobile applications that run on iOS and Android.

This guide will illustrate all of the necessary steps to successfully build and publish a Unity app with Codemagic. It will cover the basic steps such as build versioning, code signing and publishing.

You can find a complete project showcasing these steps in our Sample projects repository.

Unity licensing requirements

Building Unity apps in a cloud CI/CD environment requires a Unity Plus or a Pro license. Your license is used to activate Unity on the Codemagic build server so the iOS and Android projects can be exported. The license is returned during the publishing step of the workflow which is always run except if the build is cancelled.

You can use Unity dashboard to check the number of free seats on your license or to manually return a seat if necessary.

Adding the app to Codemagic

The apps you have available on Codemagic are listed on the Applications page. Click Add application to add a new app.

  1. If you have more than one team configured in Codemagic, select the team you wish to add the app to.
  2. Connect the repository where the source code is hosted. Detailed instructions that cover some advanced options are available here.
  3. Select the repository from the list of available repositories. Select the appropriate project type.
  4. Click Finish: Add application

Creating codemagic.yaml

In order to use codemagic.yaml for build configuration on Codemagic, it has to be committed to your repository. The name of the file must be codemagic.yaml and it must be located in the root directory of the repository. Detailed explanation can be found here.

Tip You can find codemagic.yaml examples in Codemagic Sample Projects repository.

If you prefer to write your codemagic.yaml file from scratch, you can start with this minimal configuration.

workflows:
    sample-workflow:
        name: Codemagic Sample Workflow
        max_build_duration: 120
        instance_type: mac_mini_m2

Tip You can have more than one workflow in the same codemagic.yaml file. If you are building for both the Android and iOS, simply enter both workflows as:
workflows:
    android-workflow-id:
        name: Android Sample Workflow
        # .......    
        # .......
        # .......  
    ios-workflow-id:
        name: iOS Sample Workflow
        # ......

Scan for the codemagic.yaml file by selecting a branch to scan and clicking the Check for configuration file button at the top of the page. Note that you can have different configuration files in different branches.

Code signing

All applications have to be digitally signed before they are made available to the public to confirm their author and guarantee that the code has not been altered or corrupted since it was signed.

Generating a keystore

You can create a keystore for signing your release builds with the Java Keytool utility by running the following command:

keytool -genkey -v -keystore codemagic.keystore -storetype JKS \
        -keyalg RSA -keysize 2048 -validity 10000 -alias codemagic

Keytool then prompts you to enter your personal details for creating the certificate, as well as provide passwords for the keystore and the key. It then generates the keystore as a file called codemagic.keystore in the directory you’re in. The key is valid for 10,000 days.

Uploading a keystore

  1. Open your Codemagic Team settings, and go to codemagic.yaml settings > Code signing identities.
  2. Open Android keystores tab.
  3. Upload the keystore file by clicking on Choose a file or by dragging it into the indicated frame.
  4. Enter the Keystore password, Key alias and Key password values as indicated.
  5. Enter the keystore Reference name. This is a unique name used to reference the file in codemagic.yaml
  6. Click the Add keystore button to add the keystore.

For each of the added keystore, its common name, issuer, and expiration date are displayed.

Note: The uploaded keystore cannot be downloaded from Codemagic. It is crucial that you independently store a copy of the keystore file as all subsequent builds released to Google Play should be signed with the same keystore.

However, keep the keystore file private and do not check it into a public repository.

Referencing keystores in codemagic.yaml

To tell Codemagic to fetch the uploaded keystores from the Code signing identities section during the build, list the reference of the uploaded keystore under the android_signing field.

Add the following code to the environment section of your codemagic.yaml file:

workflows:
  android-workflow:
    name: Android Workflow
    # ....
    environment:
      android_signing:
        - keystore_reference

Default environment variables are assigned by Codemagic for the values on the build machine:

  • Keystore path: CM_KEYSTORE_PATH
  • Keystore password: CM_KEYSTORE_PASSWORD
  • Key alias: CM_KEY_ALIAS
  • Key alias password: CM_KEY_PASSWORD

Creating the App Store Connect API key

Signing iOS applications requires Apple Developer Program membership.

It is recommended to create a dedicated App Store Connect API key for Codemagic in App Store Connect. To do so:

  1. Log in to App Store Connect and navigate to Users and Access > Integrations » App Store Connect API.
  2. Click on the + sign to generate a new API key.
  3. Enter the name for the key and select an access level. We recommend choosing App Manager access rights, read more about Apple Developer Program role permissions here.
  4. Click Generate.
  5. As soon as the key is generated, you can see it added to the list of active keys. Click Download API Key to save the private key for later. Note that the key can only be downloaded once.
Take note of the Issuer ID above the table of active keys as well as the Key ID of the generated key as these will be required when setting up the Apple Developer Portal integration in the Codemagic UI.

Adding the App Store Connect API key to Codemagic

  1. Open your Codemagic Team settings, go to Team integrations > Developer Portal > Manage keys.
  2. Click the Add key button.
  3. Enter the App Store Connect API key name. This is a human readable name for the key that will be used to refer to the key later in application settings.
  4. Enter the Issuer ID and Key ID values.
  5. Click on Choose a .p8 file or drag the file to upload the App Store Connect API key downloaded earlier.
  6. Click Save.

Adding the code signing certificate

Codemagic lets you upload code signing certificates as PKCS#12 archives containing both the certificate and the private key which is needed to use it. When uploading, Codemagic will ask you to provide the certificate password (if the certificate is password-protected) along with a unique Reference name, which can then be used in the codemagic.yaml configuration to fetch the specific file.

  1. Open your Codemagic Team settings, go to codemagic.yaml settings > Code signing identities.
  2. Open iOS certificates tab.
  3. Upload the certificate file by clicking on Choose a .p12 or .pem file or by dragging it into the indicated frame.
  4. Enter the Certificate password and choose a Reference name.
  5. Click Add certificate

If you have added the App Store Connect API key to Codemagic, you can also generate a new Apple Development or Apple Distribution certificate.

  1. Open your Codemagic Team settings, go to codemagic.yaml settings > Code signing identities.
  2. Open iOS certificates tab.
  3. Click Generate certificate.
  4. Provide a Reference name for the certificate.
  5. Choose the Certificate type.
  6. Select the App Store Connect API key to use.
  7. Click Create certificate.

Once the certificate has been created, Codemagic will allow you to download the certificate and provides the password for it.

After downloading, please follow the steps in the Upload certificate tab to upload the certificate to Codemagic.

Note: The certificate can be downloaded only once, right after creating it.

Note: Apple limits the number of Apple Distribution certificates to 3. If you have already reached the maximum number of certificates, the following error will be displayed:

There is a problem with the request entity - You already have a current Distribution certificate or a pending certificate request.

Similar errors can also arise in rarer cases with Apple Development certificates. To resolve the error, either remove some old certificate from the Apple Developer Portal or upload an existing certificate manually.

Existing signing certificates previously generated by Codemagic can be automatically fetched from Apple Developer Portal based on your team’s App Store Connect API key.

Fetching a certificate that was not generated by Codemagic is not possible because each certificate is linked with a private signing key to which Codemagic has no access.

  1. Open your Codemagic Team settings, go to codemagic.yaml settings > Code signing identities.
  2. Open iOS certificates tab.
  3. Click Fetch certificate.
  4. Select a certificate from the Development certificates or Distribution certificates list.
  5. Click Fetch selected.

Adding the provisioning profile

Codemagic allows you to upload a provisioning profile to be used for the application or to fetch a profile from the Apple Developer Portal.

The profile’s type, team, bundle id, and expiration date are displayed for each profile added to Code signing identities. Furthermore, Codemagic will let you know whether a matching code signing certificate is available in Code signing identities (a green checkmark in the Certificate field) or not.

Note: If your app contains app extensions, an additional provisioning profile is required for each extension. Codemagic will use the bundle identifier to find the relevant provisioning profiles. If your bundle identifier is com.example.app, the matching profiles are the ones with com.example.app and com.example.app.* as bundle identifier.

You can upload provisioning profiles with the .mobileprovision extension, providing a unique Reference name is required for each uploaded profile.

  1. Open your Codemagic Team settings, go to codemagic.yaml settings > Code signing identities.
  2. Open iOS provisioning profiles tab.
  3. Upload the provisioning profile file by clicking on Choose a .mobileprovision file or by dragging it into the indicated frame.
  4. Enter the Reference name for the profile.
  5. Click Add profile.

You can automatically fetch the provisioning profiles from the Apple Developer Portal based on your team’s App Store Connect API key. The bundle identifier is listed for every available profile along with it’s name.

The profiles are displayed grouped by category: Development profiles, Ad Hoc profiles, App Store profiles, and Enterprise profiles. For each selected profile, it is necessary to provide a unique Reference name, which can be later used in codemagic.yaml to fetch the profile.

  1. Open your Codemagic Team settings, go to codemagic.yaml settings > Code signing identities.
  2. Open iOS provisioning profiles tab.
  3. Click Fetch profiles
  4. Select the desired profile(s) and enter a Reference name for each one.
  5. Click Download selected. (scroll down if necessary)

Note: When you make essential changes to a provisioning profile, such as modifying the app ID, adding/removing capabilities from the profile identifier, or changing the certificates assigned to that profile, the provisioning profile becomes invalid. In such situations, you need to generate a new provisioning profile with these updates and then re-upload it to Codemagic.

Referencing certificates and profiles in codemagic.yaml

To fetch all uploaded signing files matching a specific distribution type and bundle identifier during the build, define the distribution_type and bundle_identifier fields in your codemagic.yaml configuration. Note that it is necessary to configure both of the fields.

workflows:
  ios-workflow:
    name: iOS Workflow 
    # ....
    environment:
      ios_signing:
        distribution_type: app_store # or: ad_hoc | development | enterprise
        bundle_identifier: com.example.id

Note: If you are publishing to the App Store or you are using TestFlight to distribute your app to test users, set the distribution_type to app_store.

When using a third party app distribution service such as Firebase App Distribution, set the distribution_type to ad_hoc

When defining the bundle identifier com.example.id, Codemagic will fetch any uploaded certificates and profiles matching the extensions as well (e.g. com.example.id.NotificationService).

Using provisioning profiles

To apply the profiles to your project during the build, add the following script before your build scripts:

  scripts:
    # ... your dependencies installation
    
    - name: Set up code signing settings on Xcode project
      script: xcode-project use-profiles
    
    # ... your build commands

Creating the App Store Connect API key

Signing macOS applications requires Apple Developer Program membership.

It is recommended to create a dedicated App Store Connect API key for Codemagic in App Store Connect. To do so:

  1. Log in to App Store Connect and navigate to Users and Access > Integrations » App Store Connect API.
  2. Click on the + sign to generate a new API key.
  3. Enter the name for the key and select an access level. We recommend choosing App Manager access rights, read more about Apple Developer Program role permissions here.
  4. Click Generate.
  5. As soon as the key is generated, you can see it added to the list of active keys. Click Download API Key to save the private key for later. Note that the key can only be downloaded once.
Take note of the Issuer ID above the table of active keys as well as the Key ID of the generated key as these will be required when setting up the Apple Developer Portal integration in the Codemagic UI.

Automatic vs Manual code signing

Signing macOS apps requires a Signing certificate (App Store development or distribution certificate in .p12 format) and a Provisioning profile. In Manual code signing you save these files as Codemagic Environment variables and manually reference them in the appropriate build steps.

In Automatic code signing, Codemagic takes care of Certificate and Provisioning profile management for you. Based on the certificate private key that you provide, Codemagic will automatically fetch the correct certificate from the App Store or create a new one if necessary.

Certificate types

There are several certificate types you can choose to sign your macOS app, depending on the distribution method you plan to use.

  • MAC_APP_DEVELOPMENT certificate allows you to build your app for internal testing and debugging.
  • MAC_APP_DISTRIBUTION certificate is used to sign a Mac app before submitting it to the Mac App Store
  • MAC_INSTALLER_DISTRIBUTION is used to sign and submit a Mac Installer Package to the Mac App Store
  • DEVELOPER_ID_APPLICATION is used to sign a Mac app before distributing it outside the Mac App Store
  • DEVELOPER_ID_INSTALLER is used to sign a Mac Installer Package before distributing it outside the Mac App Store

For example, in order to publish to Mac App Store, the application must be signed with a Mac App Distribution certificate using a Mac App Store provisioning profile. If you want to create a .pkg Installer package, you must use a Mac Installer Distribution certificate.

Obtaining the certificate private key

To enable Codemagic to automatically fetch or create the correct signing certificate on your behalf, you need to provide the corresponding certificate private key. You then have to save that key as a Codemagic environment variable.

You can create a new 2048 bit RSA key by running the command below in your terminal:

ssh-keygen -t rsa -b 2048 -m PEM -f ~/Desktop/mac_distribution_private_key -q -N ""

This new private key will be used to create a new Mac App Distribution certificate in your Apple Developer Program account if there isn’t one that already matches this private key.

  1. On the Mac which created the Mac App Distribution certificate, open the Keychain Access, located in the Applications and Utilities folder.
  2. Select the appropriate certificate entry.
  3. Right-click on it to select “Export.”
  4. In the export prompt window that appears, make sure the file format is set to Personal Information Exchange (.p12)"**.
  5. Give the file a name such as “MAC_DISTRIBUTION”, choose a location and click Save.
  6. On the next prompt, leave the password empty and click OK.
  7. Use the following openssl command to export the private key:
openssl pkcs12 -in MAC_DISTRIBUTION.p12 -nodes -nocerts | openssl rsa -out mac_distribution_private_key
  1. When prompted for the import password, just press enter. The private key will be written to a file called mac_distribution_private_key in the directory where you ran the command.

Configuring environment variables

  1. Open your Codemagic app settings, and go to the Environment variables tab.

  2. Enter CERTIFICATE_PRIVATE_KEY as the Variable name.

  3. Open the file mac_distribution_private_key with a text editor and copy the entire contents of the file, including the -----BEGIN RSA PRIVATE KEY----- and -----END RSA PRIVATE KEY----- tags. Alternatively, you can run the following command on the file:

      cat mac_distribution_private_key | pbcopy

  4. Paste into the Variable value field.

  5. Enter a variable group name, e.g. appstore_credentials. Click the button to create the group.

  6. Make sure the Secure option is selected so that the variable can be protected by encryption.

  7. Click the Add button to add the variable.

  8. Run the following command on the App Store Connect API key file that you downloaded earlier (in our example saved as codemagic_api_key.p8) to copy its content to clipboard:

    cat codemagic_api_key.p8 | pbcopy

  9. Create a new Environment variable APP_STORE_CONNECT_PRIVATE_KEY and paste the value from clipboard.

  10. Create variable APP_STORE_CONNECT_KEY_IDENTIFIER. The value is the Key ID field from App Store Connect > Users and Access > Keys.

  11. Create variable APP_STORE_CONNECT_ISSUER_ID. The value is the Issuer ID field from App Store Connect > Users and Access > Keys.

Tip: Store all the of these variables in the same group so they can be imported to codemagic.yaml workflow at once.

Environment variables have to be added to the workflow either individually or as a group. Modify your codemagic.yaml file by adding the following:

workflows:
  macos-workflow:
    name: macOS Workflow
    environment:
      groups:
        - appstore_credentials

Automatic code signing

To code sign the app, add the following commands in the scripts section of the configuration file, after all the dependencies are installed, right before the build commands.

    scripts:
      - name: Set up keychain to be used for code signing using Codemagic CLI 'keychain' command
        script: keychain initialize
      - name: Fetch signing files
        script: | 
          app-store-connect fetch-signing-files "$BUNDLE_ID" \
            --platform MAC_OS \
            --type MAC_APP_STORE \
            --create
      - name: Fetch Mac Installer Distribution certificates
        script: |  
            app-store-connect certificates list --type MAC_APP_DISTRIBUTION --save || \
            app-store-connect certificates create --type MAC_APP_DISTRIBUTION --save
      - name: Set up signing certificate
        script: keychain add-certificates
      - name: Set up code signing settings on Xcode project
        script: xcode-project use-profiles

Instead of specifying the exact bundle ID, you can use "$(xcode-project detect-bundle-id)".

Based on the specified bundle ID and provisioning profile type, Codemagic will fetch or create the relevant provisioning profile and certificate to code sign the build.

Creating the Installer package

To package your application into an .pkg Installer package and sign it with the Mac Installer Distribution certificate, use the following script:

  scripts:
    - name: Package application
      script: | 
      set -x
    
      # Command to find the path to your generated app, may be different
      APP_NAME=$(find $(pwd) -name "*.app")  
      cd $(dirname "$APP_NAME")
    
      PACKAGE_NAME=$(basename "$APP_NAME" .app).pkg
      xcrun productbuild --component "$APP_NAME" /Applications/ unsigned.pkg  # Create and unsigned package

      # Find the installer certificate common name in keychain
      INSTALLER_CERT_NAME=$(keychain list-certificates \
        | jq '.[]
        | select(.common_name
        | contains("Mac Developer Installer"))
        | .common_name' \
        | xargs)
      
      xcrun productsign --sign "$INSTALLER_CERT_NAME" unsigned.pkg "$PACKAGE_NAME" # Sign the package
    
      rm -f unsigned.pkg                                                       # Optionally remove the not needed unsigned package
Note: Don’t forget to specify the path to your generated package in the artifacts section.

Notarizing macOS applications

Notarization is a process where Apple verifies your application to make sure it has a Developer ID code signature and does not contain malicious content. All apps distributed outside the Mac App Store have to be notarized.

Notarizing an app during the Codemagic build process is possible using the altool command as follows:

xcrun altool --notarize-app -f <file> --primary-bundle-id <bundle_id>
           {-u <username> [-p <password>] | --apiKey <api_key> --apiIssuer <issuer_id>}
           [--asc-provider <name> | --team-id <id> | --asc-public-id <id>]
Code signing is not required when creating Windows Unity apps.

Configuring Unity license

Each Unity build will have to activate a valid Unity Plus or a Unity Pro license using your Unity email, Unity serial number and the Unity password.

  1. You can add these as global environment variables for your personal account by navigating to Teams > Personal Account or team by navigating to Teams > Your Team Name and then clicking on Global variables and secrets. Likewise, you can add the environment variables at the application level by clicking the Environment variables tab.

  2. Enter UNITY_EMAIL as the Variable name.

  3. Enter the email address used with your Unity ID as Variable value.

  4. Enter the variable group name, e.g. unity_credentials. Click the button to create the group.

  5. Make sure the Secure option is selected.

  6. Click the Add button to add the variable.

  7. Repeat the steps to also add UNITY_SERIAL and UNITY_PASSWORD variables.

  8. Add the unity_credentials variable group to the codemagic.yaml:

      environment:
        groups:
          - unity_credentials

Note: The UNITY_HOME environment variable is already set on the build machines to /Applications/Unity/Hub/Editor/<default-unity-version>/Unity.app.

See the default Unity version from the macOS build machine specification here.

Activating and deactivating the license

Activation

To activate a Unity license on the build machine, add the following step at the top of your scripts: section in codemagic.yaml:

  scripts:
    - name: Activate Unity license
      script: | 
        $UNITY_HOME/Contents/MacOS/Unity -batchmode -quit -logFile \
          -serial ${UNITY_SERIAL} \
          -username ${UNITY_EMAIL} \
          -password ${UNITY_PASSWORD}

When using Codemagic Windows instance types, Unity activation is performed in the same command that build the app.

Deactivation

To deactivate a Unity license on the build machine, add the following script step in the publishing: section in codemagic.yaml:

  publishing:
    scripts:
      - name: Deactivate Unity License
      script: | 
        $UNITY_HOME/Contents/MacOS/Unity -batchmode -quit -returnlicense -nographics
  publishing:
    scripts:
      - name: Deactivate Unity License
        script: | 
          /Applications/Unity\ Hub.app/Contents/Frameworks/UnityLicensingClient_V1.app/Contents/MacOS/Unity.Licensing.Client \
            --return-ulf \
            --username ${UNITY_EMAIL?} \
            --password ${UNITY_PASSWORD?}
  publishing:
    scripts:
      - name: Deactivate Unity License
        script: | 
          cmd.exe /c "$env:UNITY_HOME\\Unity.exe" -batchmode -quit -returnlicense -nographics

Note: If a build is manually cancelled before reaching the publishing section, the license WILL NOT BE RETURNED automatically. This may cause future builds to fail if there are no free license seats available.

Visit Unity dashboard to manually deactivate license.

Creating a build script

You need to create additional build script to allow building and codesigning Unity projects in headless mode. Add a new file /Assets/Editor/Build.cs with the following content:

using System.Linq;
using System;
using UnityEditor;
using UnityEngine;

public static class BuildScript
{

    [MenuItem("Build/Build Android")]
    public static void BuildAndroid()
    {

        PlayerSettings.Android.useCustomKeystore = true;
        EditorUserBuildSettings.buildAppBundle = true;

        // Set bundle version. NEW_BUILD_NUMBER environment variable is set in the codemagic.yaml 
        var versionIsSet = int.TryParse(Environment.GetEnvironmentVariable("NEW_BUILD_NUMBER"), out int version);
        if (versionIsSet)
        {
            Debug.Log($"Bundle version code set to {version}");
            PlayerSettings.Android.bundleVersionCode = version;
        }
        else
        {
            Debug.Log("Bundle version not provided");
        }

        // Set keystore name
        string keystoreName = Environment.GetEnvironmentVariable("CM_KEYSTORE_PATH");
        if (!String.IsNullOrEmpty(keystoreName))
        {
            Debug.Log($"Setting path to keystore: {keystoreName}");
            PlayerSettings.Android.keystoreName = keystoreName;
        }
        else
        {
            Debug.Log("Keystore name not provided");
        }

        // Set keystore password
        string keystorePass = Environment.GetEnvironmentVariable("CM_KEYSTORE_PASSWORD");
        if (!String.IsNullOrEmpty(keystorePass))
        {
            Debug.Log("Setting keystore password");
            PlayerSettings.Android.keystorePass = keystorePass;
        }
        else
        {
            Debug.Log("Keystore password not provided");
        }

        // Set keystore alias name
        string keyaliasName = Environment.GetEnvironmentVariable("CM_KEY_ALIAS");
        if (!String.IsNullOrEmpty(keyaliasName))
        {
            Debug.Log("Setting keystore alias");
            PlayerSettings.Android.keyaliasName = keyaliasName;
        }
        else
        {
            Debug.Log("Keystore alias not provided");
        }

        // Set keystore password
        string keyaliasPass = Environment.GetEnvironmentVariable("CM_KEY_PASSWORD");
        if (!String.IsNullOrEmpty(keyaliasPass))
        {
            Debug.Log("Setting keystore alias password");
            PlayerSettings.Android.keyaliasPass = keyaliasPass;
        }
        else
        {
            Debug.Log("Keystore alias password not provided");
        }
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
        buildPlayerOptions.locationPathName = "android/android.aab";
        buildPlayerOptions.target = BuildTarget.Android;
        buildPlayerOptions.options = BuildOptions.None;
        buildPlayerOptions.scenes = GetScenes();

        Debug.Log("Building Android");
        BuildPipeline.BuildPlayer(buildPlayerOptions);
        Debug.Log("Built Android");
    }

    [MenuItem("Build/Build iOS")]
    public static void BuildIos()
    {
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
        buildPlayerOptions.locationPathName = "ios";
        buildPlayerOptions.target = BuildTarget.iOS;
        buildPlayerOptions.options = BuildOptions.None;
        buildPlayerOptions.scenes = GetScenes();

        Debug.Log("Building iOS");
        BuildPipeline.BuildPlayer(buildPlayerOptions);
        Debug.Log("Built iOS");
    }

    [MenuItem("Build/Build Windows")]
    public static void BuildWindows()
    {
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
        buildPlayerOptions.locationPathName = "win/" + Application.productName + ".exe";
        buildPlayerOptions.target = BuildTarget.StandaloneWindows;
        buildPlayerOptions.options = BuildOptions.None;
        buildPlayerOptions.scenes = GetScenes();

        Debug.Log("Building Windows");
        BuildPipeline.BuildPlayer(buildPlayerOptions);
        Debug.Log("Built Windows");
    }

    [MenuItem("Build/Build Mac")]
    public static void BuildMac()
    {
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions();
        buildPlayerOptions.locationPathName = "mac/" + Application.productName + ".app";
        buildPlayerOptions.target = BuildTarget.StandaloneOSX;
        buildPlayerOptions.options = BuildOptions.None;
        buildPlayerOptions.scenes = GetScenes();

        Debug.Log("Building StandaloneOSX");
        BuildPipeline.BuildPlayer(buildPlayerOptions);
        Debug.Log("Built StandaloneOSX");
    }

    private static string[] GetScenes()
    {
        return (from scene in EditorBuildSettings.scenes where scene.enabled select scene.path).ToArray();
    }

}

Configuring Unity project settings

Depending on the target platform, you will need to configure some settings in your Unity project.

Project settings

Google recommends that Android applications be published to Google Play using the application bundle (.aab). You should configure the following settings in Unity before building the application bundle:

  1. Open Unity and click File > Build Settings.
  2. Make sure Android is selected in the Platform section.
  3. Check the Build App Bundle (Google Play) checkbox.
  4. Make sure that Export Project is NOT checked.
  5. Click on the Player Settings button.
  6. Expand Other Settings and check the Override Default Package Name checkbox.
  7. Enter the package name for your app, e.g. “com.domain.yourappname”.
  8. Set the Version number.
  9. Put any integer value in the Bundle Version Code. This will be overridden by the build script.
  10. Set the Minimum API Level and Target API Level to Android 11.0 (API level 30) which is required for publishing application bundles.
  11. In the Configuration section set Scripting Backend to IL2CPP.
  12. In the Target Architectures section check ARMv7 and ARM64 to support 64-bit architectures so the app is compliant with the Google Play 64-bit requirement.

Add a custom base Gradle template (Only for Unity Versions older than Unity 2022)

You will need to add custom Gradle templates so your Android builds work with Codemagic.

We need to perform this action due to the prior inclusion of a reference to jcenter() a repository that had been deprecated and proven to be unreliable, despite its intended read-only status. As a remedy, you should replace the reference to jcenter() with mavenCentral().

Once you have set up an Android mobile project on your local machine go to File > Build Settings and ensure you select Development Build and Export Project before exporting the project.

Afterward, navigate to the Export option on the Build Settings screen and proceed by clicking the Export button to save the project in a designated folder.

Finally, review the output to inspect the build.gradle. Replace the reference to jcenter() with mavenCentral() and use it as the base Gradle Template as discussed in the following steps.

OR

  1. Open Unity and File > Build Settings.
  2. Make sure Android is selected in the Platform section.
  3. Click on the Player Settings.
  4. Expand the Publishing Settings.
  5. Check the Custom Base Gradle Template.
  6. Close the project settings and build settings.

Modify the base Gradle template (Only for Unity Versions older than Unity 2022)

  1. In the project explorer expand Assets > Plugins > Android.
  2. Double click on baseProjectTemplate.gradle.
  3. Replace the entire file contents with the following:
// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN

allprojects {
    buildscript {
        repositories {**ARTIFACTORYREPOSITORY**
            google()
            mavenCentral()
        }
        dependencies {
            // If you are changing the Android Gradle Plugin version, make sure it is compatible with the Gradle version preinstalled with Unity
            // See which Gradle version is preinstalled with Unity here https://docs.unity3d.com/Manual/android-gradle-overview.html
            // See official Gradle and Android Gradle Plugin compatibility table here https://developer.android.com/studio/releases/gradle-plugin#updating-gradle
            // To specify a custom Gradle version in Unity, go do "Preferences > External Tools", uncheck "Gradle Installed with Unity (recommended)" and specify a path to a custom Gradle version
            classpath 'com.android.tools.build:gradle:4.0.1'
            **BUILD_SCRIPT_DEPS**
        }
    }
    repositories {**ARTIFACTORYREPOSITORY**
        google()
        mavenCentral()
        flatDir {
            dirs "${project(':unityLibrary').projectDir}/libs"
        }
    }
}

task clean(type: Delete) { delete rootProject.buildDir }

Set the iOS bundle identifier

You should set the bundle id of your iOS application before building the Xcode project.

  1. Open Unity and File > Build Settings.
  2. Make sure iOS is selected and click on the Player Settings button.
  3. Expand the Other Settings section.
  4. In the Identification section check the Override Default Bundle Identifier option.
  5. Set the Bundle Identifier to match the identifier name you have used in your Apple Developer Program account.

Build versioning

If you are going to publish your app to App Store Connect or Google Play, each uploaded artifact must have a new version satisfying each app store’s requirements. Codemagic allows you to easily automate this process and increment the version numbers for each build. For more information and details, see here.

One very useful method of calculating the code version is to use Codemagic command line tools to get the latest build number from Google Play and increment it by one. You can then save this as the NEW_BUILD_NUMBER environment variable that is already expected by the /Assets/Editor/Build.cs build script.

The prerequisite is a valid Google Cloud Service Account. Please follow these steps:

  1. Go to this guide and complete the steps in the Google Play section.
  2. Skip to the Creating a service account section in the same guide and complete those steps also.
  3. You now have a JSON file with the credentials.
  4. Open Codemagic UI and create a new Environment variable GCLOUD_SERVICE_ACCOUNT_CREDENTIALS.
  5. Paste the content of the downloaded JSON file in the Value field, set the group name (e.g. google_play) and make sure the Secure option is checked.
  6. Add the google_play variable group to the codemagic.yaml as well as define the PACKAGE_NAME and the GOOGLE_PLAY_TRACK:
workflows:
  android-workflow-id:
    # ....
    environment:
      android_signing:
        - keystore_reference
      groups:
        - google_play
      vars:
        PACKAGE_NAME: "io.codemagic.unitysample"
        GOOGLE_PLAY_TRACK: alpha
  1. Modify the build script to fetch the latest build number from Google Play, increment it and pass it as command line argument to the build command
  scripts:
    - name: Set the build number
      script: | 
        export NEW_BUILD_NUMBER=$(($(google-play get-latest-build-number \
          --package-name "$PACKAGE_NAME" \
          --tracks="$GOOGLE_PLAY_TRACK") + 1))

In order to get the latest build number from App Store or TestFlight, you will need the App Store credentials as well as the Application Apple ID. This is an automatically generated ID assigned to your app and it can be found under General > App Information > Apple ID under your application in App Store Connect.

  1. Add the Application Apple ID to the codemagic.yaml as a variable
  2. Add the script to get the latest build number using app-store-connect, increment it and pass it as command line argument to the build command:
workflows:
  ios-workflow:
    name: iOS Workflow
    integrations:
      app_store_connect: <App Store Connect API key name>
    environment:
      ios_signing:
        distribution_type: app_store
        bundle_identifier: io.codemagic.unitysample
      vars:
        APP_STORE_APPLE_ID: 1555555551
    scripts:
      - name: Set the build number
        script: | 
          BUILD_NUMBER=($(app-store-connect get-latest-app-store-build-number "$APP_STORE_APPLE_ID") + 1)
          cd ios
          agvtool new-version -all $BUILD_NUMBER

Building the app

Add the following scripts to your codemagic.yaml file in order to prepare the build environment and start the actual build process. In this step you can also define the build artifacts you are interested in. These files will be available for download when the build finishes. For more information about artifacts, see here.

  environment:
    #...
  scripts:
    - name: Activate Unity license
      script: #...
    - name: Set the build number
      script: #... 
    - name: Build the project
      script: | 
        $UNITY_HOME/Contents/MacOS/Unity -batchmode \
          -quit \
          -logFile \
          -projectPath . \
          -executeMethod BuildScript.BuildAndroid \
          -nographics
    artifacts:
      - android/*.aab
  environment:
    #...
    vars:
      UNITY_IOS_DIR: ios
      XCODE_PROJECT: "Unity-iPhone.xcodeproj"
      XCODE_SCHEME: "Unity-iPhone"
  scripts:
    - name: Activate Unity license
      script: #...
    - name: Generate the Xcode project from Unity
      script: | 
        $UNITY_HOME/Contents/MacOS/Unity -batchmode \
          -quit \
          -logFile \
          -projectPath . \
          -executeMethod BuildScript.BuildIos \
          -nographics
    - name: Set up code signing settings on Xcode project
      script: | 
        xcode-project use-profiles
    - name: Set the build number
      script: #...
    - name: Build the project
      script: | 
        xcode-project build-ipa --project "$UNITY_IOS_DIR/$XCODE_PROJECT" --scheme "$XCODE_SCHEME"
    artifacts:
      - build/ios/ipa/*.ipa
      - $HOME/Library/Developer/Xcode/DerivedData/**/Build/**/*.dSYM

Note: If you are using Pod files and Xcode workspace, replace the Build the project step by this (don’t forget to configure the XCODE_WORKSPACE variable):

    - name: Install pods
      script: | 
        pod install
    - name: Build the project
      script: | 
        xcode-project build-ipa \
          --workspace "$UNITY_IOS_DIR/$XCODE_WORKSPACE" \
          --scheme "$XCODE_SCHEME"
  environment:
    #...
    vars:
      UNITY_MAC_DIR: mac
      BUNDLE_ID: "io.codemagic.unitysample"
  scripts:
    - name: Set up keychain
      script: | 
        keychain initialize
    - name: Fetch signing files
      script: | 
        app-store-connect fetch-signing-files "$BUNDLE_ID" \
          --type MAC_APP_STORE \
          --platform MAC_OS \
          --create
    - name: Fetch Mac Installer Distribution certificates
      script: | 
        app-store-connect certificates list --type MAC_INSTALLER_DISTRIBUTION --save || \
        app-store-connect certificates create --type MAC_INSTALLER_DISTRIBUTION --save 
    - name: Add certs to keychain
      script: | 
        keychain add-certificates
    - name: Set up code signing settings on Xcode project
      script: | 
        xcode-project use-profiles
    - name: Activate License
      script: #...
    - name: Build the project
      script: | 
        $UNITY_HOME/Contents/MacOS/Unity -batchmode -quit -logFile \
          -projectPath . \
          -executeMethod BuildScript.BuildMac \
          -nographics
    - name: Package macOS application
      script: | 
        set -x
        #
        # Command to find the path to your generated app
        APP_NAME=$(find $(pwd) -name "*.app")
        cd $(dirname "$APP_NAME")
        PACKAGE_NAME=$(basename "$APP_NAME" .app).pkg
        #
        # Create an unsigned package
        xcrun productbuild \
          --component "$APP_NAME" \
          /Applications/ unsigned.pkg
        #
        # Find the installer certificate common name in keychain
        INSTALLER_CERT_NAME=$(keychain list-certificates \
            | jq '.[]
              | select(.common_name
              | contains("Mac Developer Installer"))
              | .common_name' \
            | xargs)
        #
        # Sign the package
        xcrun productsign \
          --sign "$INSTALLER_CERT_NAME" \
          unsigned.pkg "$PACKAGE_NAME"
        #
        # Optionally remove the not needed unsigned package
        rm -f unsigned.pkg
    artifacts:
      - $UNITY_MAC_DIR/*.app
      - $UNITY_MAC_DIR/*.pkg
  scripts:
    - name: Activate & Build Unity Using a Command Prompt
      script: | 
        cmd.exe /c "$env:UNITY_HOME\\Unity.exe" ^
          -batchmode -quit -logFile ^
          -projectPath . ^
          -executeMethod BuildScript.BuildWindows ^
          -nographics ^
          -serial $env:UNITY_SERIAL ^
          -username $env:UNITY_EMAIL ^
          -password $env:UNITY_PASSWORD
    - name: Export Unity
      script: | 
        cd windows
        7z a -r release.zip ./*
    artifacts:
      - windows/*.zip
Note: Read how to use different Unity version here.

Publishing

Codemagic offers a wide array of options for app publishing and the list of partners and integrations is continuously growing. For the most up-to-date information, check the guides in the Configuration > Publishing section of these docs. To get more details on the publishing options presented in this guide, please check the Email publishing, the Google Play Store publishing and the App Store Connect.

Email publishing

If the build finishes successfully, release notes (if passed), and the generated artifacts will be published to the provided email address(es). If the build fails, an email with a link to build logs will be sent.

If you don’t want to receive an email notification on build success or failure, you can set success to false or failure to false accordingly.

workflows:
  sample-workflow-id:
    environment: 
      # ...
    scripts: 
      # ...
    publishing: 
      email:
        recipients:
          - user_1@example.com
          - user_2@example.com
        notify:
          success: true
          failure: false

Publishing to Google Play and App Store

Publishing apps to Google Play requires you to set up a service account in Google Play Console and save the content of the JSON key file to a secure environment variable as explained above in Android Build Versioning steps 1-5. Configuring Google Play publishing is simple as you only need to provide credentials and choose the desired track. If the app is in draft status, please also include the submit_as_draft: true or promote the app status in Google Play.

react-native-android:
  # ... 
  publishing:
    # ...
    google_play:
      credentials: $GCLOUD_SERVICE_ACCOUNT_CREDENTIALS
      track: internal
      submit_as_draft: true

Codemagic enables you to automatically publish your iOS or macOS app to App Store Connect for beta testing with TestFlight or distributing the app to users via App Store. Codemagic uses the App Store Connect API key for authenticating communication with Apple’s services. You can read more about generating an API key from Apple’s documentation page.

Please note that:

  1. for App Store Connect publishing, the provided key needs to have App Manager permission,
  2. and in order to submit your iOS application to App Store Connect, it must be code signed with a distribution certificate.

The following snippet demonstrates how to authenticate with and upload the IPA to App Store Connect, submit the build to beta tester groups in TestFlight and configure releasing the app to App Store. See additional configuration options for App Store Connect publishing here.

Note: Please note that you will need to create an app record in App Store Connect before you can automate publishing with Codemagic. It is recommended to upload the very first version of the app manually. Suppose you have set up an app record but have not manually uploaded the app’s first version. In that case, manual configuration of the settings must be done on App Store Connect after the build is complete, such as uploading the required screenshots and providing the values for the privacy policy URL and application category.
# Integration section is required to make use of the keys stored in 
# Codemagic UI under Apple Developer Portal integration.
integrations:
  app_store_connect: <App Store Connect API key name>

publishing:
  app_store_connect:
    # Use referenced App Store Connect API key to authenticate binary upload
    auth: integration 

    # Configuration related to TestFlight (optional)

    # Optional boolean, defaults to false. Whether or not to submit the uploaded
    # build to TestFlight beta review. Required for distributing to beta groups.
    # Note: This action is performed during post-processing.
    submit_to_testflight: true 

    # Optional boolean, defaults to false. Set to true to automatically expire 
    # previous build in review or waiting for review in Testflight before
    # submitting a new build to beta review. Expired builds will no longer be available for testers.
    # Note: This action is performed during post-processing.
    expire_build_submitted_for_review: true

    # Specify the names of beta tester groups that will get access to the build 
    # once it has passed beta review.
    beta_groups: 
      - group name 1
      - group name 2
    
    # Configuration related to App Store (optional)

    # Optional boolean, defaults to false. Whether or not to submit the uploaded
    # build to App Store review. Note: This action is performed during post-processing.
    submit_to_app_store: true

    # Optional boolean, defaults to false. Set to true to cancel the previous 
    # submission (if applicable) when submitting a new build to App Store review.
    # This allows automatically submitting a new build for review if a previous submission exists.
    # Note: This action is performed during post-processing.
    cancel_previous_submissions: true
    
    # Optional, defaults to MANUAL. Supported values: MANUAL, AFTER_APPROVAL or SCHEDULED
    release_type: SCHEDULED

    # Optional. Timezone-aware ISO8601 timestamp with hour precision when scheduling
    # the release. This can be only used when release type is set to SCHEDULED.
    # It cannot be set to a date in the past.
    earliest_release_date: 2021-12-01T14:00:00+00:00 
    
    # Optional. The name of the person or entity that owns the exclusive rights
    # to your app, preceded by the year the rights were obtained.
    copyright: 2021 Nevercode Ltd
  
    # Optional boolean. Whether or not to release an App Store version update in phases.
    # With this option turned on, your version update will be released over a 7-day period
    # to a percentage of your users (selected at random by their Apple ID) with automatic
    # updates turned on. Learn more from 
    # https://developer.apple.com/help/app-store-connect/update-your-app/release-a-version-update-in-phases.
    # If not specified, then App Store version default phased release configuration is reused.
    phased_release: true

App Store post processing

When publishing your app to TestFlight or the App Store, you will be asked if your app uses encryption.

You can automate your answer to this question by setting the key ITSAppUsesNonExemptEncryption in your app’s Info.plist file and set the value to NO if the app doesn’t use encryption.

For more details about complying with encryption export regulations, please see here.

A Unity post-processing script can be used to set values in the Info.plist of the Xcode project.

Create a new file /Assets/Editor/PostProcessing.cs with the following content:

using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using System.IO;

public class IosBuildPostprocessor
{

    [PostProcessBuild(1)]
    public static void EditPlist(BuildTarget target, string path)
    {
        if (target != BuildTarget.iOS)
            return;


        string plistPath = path + "/Info.plist";
        PlistDocument plist = new PlistDocument();
        plist.ReadFromFile(plistPath);

        PlistElementDict rootDict = plist.root;

        // Add ITSAppUsesNonExemptEncryption to Info.plist
        rootDict.SetString("ITSAppUsesNonExemptEncryption", "false");


        File.WriteAllText(plistPath, plist.WriteToString());
    }
}

Caching

Caching certain directories can significantly speed up the build process by avoiding unnecessary recompilation or re-downloading of dependencies. Here are some directories that you should consider caching:

  • Library: The Library directory in your Unity project contains various generated files, including the Unity package cache, script compilation artifacts, and build settings.

  • Temp: The Temp directory holds temporary files generated during the build process. Caching this directory can prevent redundant regeneration of temporary data, such as asset import caches, asset bundle dependencies, and shader compilations.

Using Codemagic’s caching system

You can cache files for each workflow you have by specifying the paths you want to cache like this:

    cache:
      cache_paths:
        - $CM_BUILD_DIR/Library
        - $CM_BUILD_DIR/Temp

Please refer to the cache usage limits here.

Using your own external storage system

If your caching step is being skipped because it’s exceeding the maximum allowed cache usage limit then you can use some external storage to store your caching files.

In the following example we are going to use AWS S3.

Using AWS S3

In order to use AWS S3, you need to configure your access credentials in Codemagic. You can follow the instructions provided by Amazon to create your account and get the necessary credentials.

  1. Open your Codemagic app settings, and go to the Environment variables tab.
  2. Enter the desired Variable name, e.g. AWS_ACCESS_KEY_ID.
  3. Enter the required value as Variable value.
  4. Enter the variable group name, e.g. aws_credentials. Click the button to create the group.
  5. Make sure the Secure option is selected.
  6. Click the Add button to add the variable.
  7. Repeat the process to also add the AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION variables.
  8. Import the aws_credentials group.

Add the script below to your scripts section before your build script to check if S3 bucket has an old cached file.

- name: Check S3 bucket for cached files
  script: | 
    if echo $(aws s3 ls s3://<BUCKET_NAME>) | grep -q library-<APP_NAME>.tar.gz ; then 
      echo "Caching files were found in the S3 bucket."; 
      aws s3 cp s3://<BUCKET_NAME>/library-<APP_NAME>.tar.gz ${CM_BUILD_DIR}
      gunzip < library-<APP_NAME>.tar.gz | tar -xv
    else 
      echo "No caching files were found in the S3 bucket."; 
    fi
Replace <BUCKET_NAME> with your actual bucket name and <APP_NAME> with your app name.

At the publishing section add this script to make a copy of your Library folder and upload it.

publishing:
  scripts:
    - name: Uploading caching files to S3 bucket
      script: | 
        tar -cv Library/ | gzip > library-<APP_NAME>.tar.gz
        aws s3 cp library-<APP_NAME>.tar.gz s3://<BUCKET_NAME>

It’s important to note that the effectiveness of caching depends on the nature of your project and how frequently different directories change. It’s recommended to experiment with caching different directories and measure the impact on your build times to find the optimal configuration for your Codemagic pipeline.

Conclusion

Having followed all of the above steps, you now have a working codemagic.yaml file that allows you to build, code sign, automatically version and publish your project using Codemagic CI/CD. Save your work, commit the changes to the repository, open the app in the Codemagic UI and start the build to see it in action.

workflows:
  unity-android-workflow:
    name: Unity Android Workflow
    max_build_duration: 120
    environment:
      android_signing:
        - keystore_reference
      groups:
        - unity_credentials
        - google_play
      vars:
        BUILD_SCRIPT: BuildAndroid
        GOOGLE_PLAY_TRACK: alpha
        PACKAGE_NAME: "io.codemagic.unitysample"
    scripts:
      - name: Activate Unity License
        script: | 
          $UNITY_HOME/Contents/MacOS/Unity -batchmode -quit -logFile \
            -serial ${UNITY_SERIAL} \
            -username ${UNITY_EMAIL} \
            -password ${UNITY_PASSWORD}
      - name: Set the build number
        script: | 
          export NEW_BUILD_NUMBER=$(($(google-play get-latest-build-number \
            --package-name "$PACKAGE_NAME" \
            --tracks="$GOOGLE_PLAY_TRACK") + 1))
      - name: Build the project
        script: | 
          $UNITY_HOME/Contents/MacOS/Unity -batchmode \
            -quit \
            -logFile \
            -projectPath . \
            -executeMethod BuildScript.BuildAndroid \
            -nographics
    artifacts:
      - android/*.aab
    publishing:
      scripts:
        - name: Deactivate Unity License
          script: | 
            /Applications/Unity\ Hub.app/Contents/Frameworks/UnityLicensingClient_V1.app/Contents/MacOS/Unity.Licensing.Client \
            --return-ulf \
            --username ${UNITY_EMAIL} \
            --password ${UNITY_PASSWORD}
      email:
        recipients:
          - user_1@example.com
          - user_2@example.com
        notify:
          success: true
          failure: false
      google_play:
        credentials: $GCLOUD_SERVICE_ACCOUNT_CREDENTIALS
        track: GOOGLE_PLAY_TRACK
        submit_as_draft: true
workflows:
  unity-ios-workflow:
    name: Unity iOS Workflow
    max_build_duration: 120
    integrations:
      app_store_connect: codemagic
    environment:
      ios_signing:
        distribution_type: app_store
        bundle_identifier: io.codemagic.unitysample
      groups:
        - unity_credentials
      vars:
        UNITY_IOS_DIR: ios
        XCODE_PROJECT: "Unity-iPhone.xcodeproj"
        XCODE_SCHEME: "Unity-iPhone"
        BUNDLE_ID: "io.codemagic.unitysample"
        APP_STORE_APPLE_ID: 1555555551
    scripts:
      - name: Activate Unity license
        script: | 
          $UNITY_HOME/Contents/MacOS/Unity -batchmode -quit -logFile \
            -serial ${UNITY_SERIAL} \
            -username ${UNITY_EMAIL} \
            -password ${UNITY_PASSWORD}
      - name: Generate the Xcode project from Unity
        script: | 
          $UNITY_HOME/Contents/MacOS/Unity -batchmode \
            -quit \
            -logFile \
            -projectPath . \
            -executeMethod BuildScript.BuildIos \
            -nographics
      - name: Set up code signing settings on Xcode project
        script: | 
          xcode-project use-profiles
      - name: Set the build number
        script: | 
          BUILD_NUMBER=($(app-store-connect get-latest-app-store-build-number "$APP_STORE_APPLE_ID") + 1)
          cd $UNITY_IOS_DIR
          agvtool new-version -all $BUILD_NUMBER
      - name: Build the project
        script: | 
          xcode-project build-ipa \
            --project "$UNITY_IOS_DIR/$XCODE_PROJECT" \
            --scheme "$XCODE_SCHEME"
    artifacts:
      - build/ios/ipa/*.ipa
      - $HOME/Library/Developer/Xcode/DerivedData/**/Build/**/*.dSYM
    publishing:
      scripts:
        - name: Deactivate Unity License
          script: | 
            /Applications/Unity\ Hub.app/Contents/Frameworks/UnityLicensingClient_V1.app/Contents/MacOS/Unity.Licensing.Client \
            --return-ulf \
            --username ${UNITY_EMAIL} \
            --password ${UNITY_PASSWORD}
      email:
        recipients:
          - user_1@example.com
          - user_2@example.com
        notify:
          success: true
          failure: false
      app_store_connect:
        auth: integration
        #
        # Configuration related to TestFlight (optional)
        # Note: This action is performed during post-processing.
        submit_to_testflight: true 
        #
        # Specify the names of beta tester groups that will get access 
        # to the build once it has passed beta review.
        beta_groups:
          - group name 1
          - group name 2
        #
        # Configuration related to App Store (optional)
        # Note: This action is performed during post-processing.
        submit_to_app_store: true
workflows:
  unity-macos-workflow:
    name: Unity Mac Workflow
    max_build_duration: 120
    environment:
      groups:
        - unity_credentials
        - appstore_credentials
      vars:
        UNITY_MAC_DIR: mac
        XCODE_PROJECT: "Unity-iPhone.xcodeproj"
        XCODE_SCHEME: "Unity-iPhone"
        BUNDLE_ID: "io.codemagic.unitysample"
    scripts:
      - name: Activate Unity license
        script: | 
          $UNITY_HOME/Contents/MacOS/Unity -batchmode -quit -logFile \
            -serial ${UNITY_SERIAL} \
            -username ${UNITY_EMAIL} \
            -password ${UNITY_PASSWORD}
      - name: Set up keychain
        script: | 
          keychain initialize
      - name: Fetch signing files
        script: | 
          app-store-connect fetch-signing-files "$BUNDLE_ID" \
            --platform MAC_OS \
            --type MAC_APP_STORE \
            --create
      - name: Fetch Mac Installer Distribution certificates
        script: |  
            app-store-connect certificates list --type MAC_APP_DISTRIBUTION --save || \
            app-store-connect certificates create --type MAC_APP_DISTRIBUTION --save
      - name: Add certs to keychain
        script: | 
          keychain add-certificates
      - name: Set up code signing settings on Xcode project
        script: | 
          xcode-project use-profiles    
      - name: Build the project
        script: | 
          $UNITY_HOME/Contents/MacOS/Unity -batchmode -quit -logFile \
            -projectPath . \
            -executeMethod BuildScript.BuildMac \
            -nographics
      - name: Package application
        script: | 
          set -x

          APP_NAME=$(find $(pwd) -name "*.app")  
          cd $(dirname "$APP_NAME")
    
          PACKAGE_NAME=$(basename "$APP_NAME" .app).pkg
          xcrun productbuild \
            --component "$APP_NAME" \
            /Applications/ unsigned.pkg

          INSTALLER_CERT_NAME=$(keychain list-certificates \
            | jq '.[]
            | select(.common_name
            | contains("Mac Developer Installer"))
            | .common_name' \
            | xargs)
      
          xcrun productsign \
            --sign "$INSTALLER_CERT_NAME" \
            unsigned.pkg \
            "$PACKAGE_NAME"
          rm -f unsigned.pkg            
    artifacts:
      - $UNITY_MAC_DIR/*.app
      - $UNITY_MAC_DIR/*.pkg
    publishing:
      scripts:
        - name: Deactivate Unity License
          script: | 
            /Applications/Unity\ Hub.app/Contents/Frameworks/UnityLicensingClient_V1.app/Contents/MacOS/Unity.Licensing.Client \
            --return-ulf \
            --username ${UNITY_EMAIL} \
            --password ${UNITY_PASSWORD}
      email:
        recipients:
          - user_1@example.com
          - user_2@example.com
        notify:
          success: true
          failure: false
      app_store_connect:
        api_key: $APP_STORE_CONNECT_PRIVATE_KEY
        key_id: $APP_STORE_CONNECT_KEY_IDENTIFIER
        issuer_id: $APP_STORE_CONNECT_ISSUER_ID
        submit_to_testflight: false 
        submit_to_app_store: true
workflows:
  unity-windows-workflow:
    name: Unity Windows Workflow
    max_build_duration: 120
    instance_type: windows_x2
    environment:
      groups:
        - unity_credentials
    scripts:
      - name: Activate & Build Unity Using a Command Prompt
        script: | 
          cmd.exe /c "$env:UNITY_HOME\\Unity.exe" ^
            -batchmode -quit -logFile ^
            -projectPath . ^
            -executeMethod BuildScript.BuildWindows ^
            -nographics ^
            -serial $env:UNITY_SERIAL ^
            -username $env:UNITY_EMAIL ^
            -password $env:UNITY_PASSWORD
      - name: Export Unity
        script: | 
          cd windows
          7z a -r release.zip ./*
    artifacts:
      - windows/*.zip
    publishing:
      scripts:
        - name: Deactivate Unity License
          script: | 
            cmd.exe /c "$env:UNITY_HOME\\Unity.exe" -batchmode -quit -returnlicense -nographics
      email:
        recipients:
          - user_1@example.com
          - user_2@example.com
        notify:
          success: true
          failure: false
      slack:
        channel: "#your-channel-name"
        notify_on_build_start: true

Next steps

While this basic workflow configuration is incredibly useful, it is certainly not the end of the road and there are numerous advanced actions that Codemagic can help you with.

We encourage you to investigate Running tests with Codemagic to get you started with testing, as well as additional guides such as the one on running tests on Firebase Test Lab or Registering iOS test devices.

Documentation on using codemagic.yaml teaches you to configure additional options such as changing the instance type on which to build, or configuring builds to be automatically triggered on repository events.