Skip to main content
tutorial

Python for Unity Developers: Automate Your Builds in 5 Steps

Angry Shark Studio
15 min
Unity Python Automation DevOps Build Pipeline Tutorial Unity Build Automation Python Unity Integration

Difficulty Level: Intermediate

Manual Unity builds for multiple platforms consume valuable development time. Building for Windows, Mac, Android, WebGL, and iOS individually requires repetitive clicking through Unity’s interface for each platform.

Python automation solves this inefficiency by enabling single-command builds for all platforms simultaneously. This approach requires no complex architecture or runtime integrationβ€”just straightforward automation scripts. For more Unity optimization techniques, check our mobile performance guide.

Unity build automation with Python is the process of using Python scripts to automatically compile Unity projects for multiple platforms (Windows, Mac, Android, WebGL, iOS) without manual intervention. This approach eliminates the need to manually switch platforms and click through Unity’s Build Settings dialog for each target platform, reducing build time from hours to minutes while preventing human error in the build process.

Why Python for Unity Build Automation?

According to Unity’s official documentation, command-line builds provide consistent, repeatable results essential for professional game development.

Unity’s built-in Build Settings have limitations for professional development workflows:

  1. Manual builds don’t scale - Building for 5 platforms means clicking through dialogs 5 times
  2. Human error - Forget to change one setting and your Android build has Windows resolution
  3. No automation - Can’t schedule builds or integrate with CI/CD
  4. No reporting - No automatic tracking of build times or success rates

Python excels at automation, file operations, and process managementβ€”exactly what we need for professional Unity development and build automation. This automation expertise is crucial in our AI development services where we integrate Python-based AI systems with Unity applications.

What We’re Building

By the end of this tutorial, you’ll have:

  • A simple Unity project to test builds
  • Python scripts that auto-detect all project settings
  • Zero-configuration builds for multiple platforms
  • Automated build reports showing success/failure and build times

The best part? The Python scripts live right inside your Unity project and require almost no manual setup!

Prerequisites

  • Unity 2021.3 LTS or newer installed
  • Python 3.8+ installed (Download Python)
  • TextMeshPro package imported in Unity (Window β†’ TextMeshPro β†’ Import TMP Essential Resources)
  • Basic familiarity with Unity
  • No Python experience required!

Step 1: Create a Simple Unity Test Project

First, create a minimal Unity project to test the automation. A simple button interface will verify build functionality.

Setting Up the Unity Project

  1. Create a new Unity project called SimpleUnityProject
  2. Create a new scene: Assets/Scenes/MainScene.unity
  3. Add a UI Canvas (Right-click in Hierarchy β†’ UI β†’ Canvas)
  4. Add a background:
    • Right-click Canvas β†’ UI β†’ Image
    • Set anchors to stretch (Alt+Shift+click bottom-right anchor preset)
    • Set color to a pleasant blue (#4A90E2)
  5. Add a button:
    • Right-click Canvas β†’ UI β†’ Button - TextMeshPro
    • Center it on screen
    • Change text to β€œHello Build Automation!”
    • Set button size to 300x80 for better visibility

Add Simple Interaction

Create a new script Assets/Scripts/ButtonHandler.cs:

using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class ButtonHandler : MonoBehaviour 
{
    [SerializeField] private Button button;
    [SerializeField] private TextMeshProUGUI textToChange;

    private int clickCount;

    private void OnEnable() 
    {
        button.onClick.AddListener(OnButtonClick);
    }

    private void OnDisable() 
    {
        button.onClick.RemoveListener(OnButtonClick);
    }

    private void OnButtonClick() 
    {
        clickCount++;
        textToChange.text = $"Clicked {clickCount} times!";
        Debug.Log($"Button clicked {clickCount} times");
    }

    private void OnValidate() 
    {
        if (!button) button = GetComponent<Button>();
        if (!textToChange) textToChange = GetComponentInChildren<TextMeshProUGUI>();
    }
}

Setting it up:

  1. Attach this script to your button GameObject
  2. In the Inspector, drag the Button component to the β€œButton” field
  3. Drag the TextMeshProUGUI component to the β€œText To Change” field
  4. Save the scene and set it as the default in Build Settings

Configure Build Settings

  1. Open File β†’ Build Settings
  2. Add your MainScene to β€œScenes in Build”
  3. Set Company Name and Product Name (e.g., β€œMyCompany” and β€œBuildTest”)

The test project is now ready for automated building.

Step 2: Understanding Unity’s Command Line Interface

Unity’s command-line interface enables building projects without the editor GUI. This functionality forms the foundation of build automation.

Technical diagram of Unity build automation pipeline: Python script connects to Unity Editor in batch mode, then branches to build Windows, macOS, Android and WebGL versions

Unity Batch Mode Basics

Unity can run in β€œbatch mode”—no GUI, just pure processing. Here are the key flags:

  • -batchmode: Run without graphics
  • -quit: Exit when done
  • -nographics: Don’t initialize graphics device
  • -projectPath: Path to Unity project
  • -executeMethod: Call a static method
  • -logFile: Where to save logs

Build Command Structure

A typical Unity build command looks like this:

Unity.exe -batchmode -quit -projectPath "C:/MyProject" -executeMethod BuildScript.BuildWindows -logFile build.log

Unity requires a custom build script for command-line operations. Create the following script:

Create Unity Build Script

Create Assets/Scripts/Editor/CommandLineBuild.cs:

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

public class CommandLineBuild
{
    // Get scenes from Build Settings automatically
    private static string[] GetScenePaths()
    {
        return EditorBuildSettings.scenes
            .Where(scene => scene.enabled)
            .Select(scene => scene.path)
            .ToArray();
    }

    // Get product name from Player Settings
    private static string GetProductName()
    {
        return PlayerSettings.productName;
    }

    // Get bundle version from Player Settings
    private static string GetBundleVersion()
    {
        return PlayerSettings.bundleVersion;
    }

    // Ensure build directory exists
    private static void EnsureDirectoryExists(string filePath)
    {
        string directory = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
    }

    public static void BuildWindows()
    {
        string productName = GetProductName();
        string bundleVersion = GetBundleVersion();
        string outputPath = $"Builds/Windows/{bundleVersion}/{productName}.exe";
        
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions
        {
            scenes = GetScenePaths(),
            locationPathName = outputPath,
            target = BuildTarget.StandaloneWindows64,
            options = BuildOptions.None
        };

        Debug.Log($"Building Windows: {productName}");
        EnsureDirectoryExists(outputPath);

        var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
        if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
        {
            EditorApplication.Exit(1);
        }
    }

    public static void BuildMac()
    {
        string productName = GetProductName();
        string bundleVersion = GetBundleVersion();
        string outputPath = $"Builds/Mac/{bundleVersion}/{productName}.app";
        
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions
        {
            scenes = GetScenePaths(),
            locationPathName = outputPath,
            target = BuildTarget.StandaloneOSX,
            options = BuildOptions.None
        };

        EnsureDirectoryExists(outputPath);
        var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
        if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
        {
            EditorApplication.Exit(1);
        }
    }

    public static void BuildAndroid()
    {
        string productName = GetProductName();
        string bundleVersion = GetBundleVersion();
        string outputPath = $"Builds/Android/{bundleVersion}/{productName}.apk";
        
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions
        {
            scenes = GetScenePaths(),
            locationPathName = outputPath,
            target = BuildTarget.Android,
            options = BuildOptions.None
        };

        EnsureDirectoryExists(outputPath);
        var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
        if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
        {
            EditorApplication.Exit(1);
        }
    }

    public static void BuildWebGL()
    {
        string productName = GetProductName();
        string bundleVersion = GetBundleVersion();
        string outputPath = $"Builds/WebGL/{bundleVersion}/{productName}";
        
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions
        {
            scenes = GetScenePaths(),
            locationPathName = outputPath,
            target = BuildTarget.WebGL,
            options = BuildOptions.None
        };

        EnsureDirectoryExists(outputPath);
        var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
        if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
        {
            EditorApplication.Exit(1);
        }
    }

    public static void BuildiOS()
    {
        // Check if running on macOS
        if (Application.platform != RuntimePlatform.OSXEditor)
        {
            Debug.LogError("iOS builds can only be created on macOS!");
            EditorApplication.Exit(1);
        }
        
        string productName = GetProductName();
        string bundleVersion = GetBundleVersion();
        string outputPath = $"Builds/iOS/{bundleVersion}/{productName}";
        
        BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions
        {
            scenes = GetScenePaths(),
            locationPathName = outputPath,
            target = BuildTarget.iOS,
            options = BuildOptions.None
        };

        EnsureDirectoryExists(outputPath);
        var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
        if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
        {
            EditorApplication.Exit(1);
        }
    }
}

Key improvements:

  • No hardcoded values - Scenes come from Build Settings, output names from Product Name
  • Version folders - Builds are organized by version (e.g., Builds/Windows/1.0.0/GameName.exe)
  • Auto-detection - Everything is read from Unity’s configuration
  • Error handling - Returns error code if build fails
  • Directory creation - Automatically creates build folders including version subdirectories

Important: Add scenes to Build Settings (File β†’ Build Settings) before running automation.

Step 3: Your First Python Build Script

This section covers Python script implementation for build automation.

Setting Up Python Scripts Inside Unity

All automation scripts reside within the Unity project structure. Create a BuildAutomation folder:

SimpleUnityProject/
β”œβ”€β”€ Assets/
β”œβ”€β”€ ProjectSettings/
β”œβ”€β”€ BuildAutomation/      # Python scripts live here!
β”‚   β”œβ”€β”€ build.py          # Our main script
β”‚   β”œβ”€β”€ .env.example      # Template for Unity path
β”‚   β”œβ”€β”€ .env              # Your actual Unity path (gitignored)
β”‚   └── requirements.txt  # Python dependencies
└── Builds/               # Build outputs

Install Python Dependencies

First, let’s install our dependencies. Create BuildAutomation/requirements.txt:

python-dotenv==1.0.0  # For loading Unity path from .env file
rich==13.7.0          # For beautiful console output with colors and formatting
click==8.1.7          # For professional command-line interface

Install dependencies:

cd BuildAutomation
pip install -r requirements.txt

Configure Unity Path

Create BuildAutomation/.env.example:

# Copy this file to .env and update with your Unity installation path

# Windows example:
UNITY_PATH="C:/Program Files/Unity/Hub/Editor/2021.3.16f1/Editor/Unity.exe"

# macOS example:
# UNITY_PATH="/Applications/Unity/Hub/Editor/2021.3.16f1/Unity.app/Contents/MacOS/Unity"

# Linux example:
# UNITY_PATH="/home/username/Unity/Hub/Editor/2021.3.16f1/Editor/Unity"

Now copy this to .env and update with your actual Unity path:

cp .env.example .env
# Edit .env with your Unity installation path

Your First Build Script

Create BuildAutomation/build.py:

import subprocess
import os
import sys
import re
import time
from pathlib import Path
from dotenv import load_dotenv

class UnityAutoBuilder:
    def __init__(self):
        """Initialize with auto-detected settings"""
        # Load environment variables
        load_dotenv()
        
        # Auto-detect everything!
        self.project_root = self.find_project_root()
        self.project_name = self.get_project_name()
        self.unity_path = os.getenv('UNITY_PATH')
        
        if not self.unity_path:
            print("Unity path not found!")
            print("Please set UNITY_PATH in .env file")
            print("Example: UNITY_PATH=\"C:/Program Files/Unity/Hub/Editor/2021.3.16f1/Editor/Unity.exe\"")
            sys.exit(1)
        
        print(f"Project: {self.project_name}")
        print(f"Root: {self.project_root}")
        print(f"Unity: {os.path.basename(os.path.dirname(self.unity_path))}")
        
    def find_project_root(self):
        """Find Unity project root by looking for Assets folder"""
        # Start from BuildAutomation folder
        current = os.path.dirname(os.path.abspath(__file__))
        
        # Go up until we find Assets and ProjectSettings
        while current != os.path.dirname(current):
            if (os.path.exists(os.path.join(current, "Assets")) and 
                os.path.exists(os.path.join(current, "ProjectSettings"))):
                return current
            current = os.path.dirname(current)
        
        print("Unity project root not found!")
        print("Make sure this script is inside your Unity project")
        sys.exit(1)
    
    def get_project_name(self):
        """Extract project name from ProjectSettings.asset"""
        settings_path = os.path.join(self.project_root, "ProjectSettings", "ProjectSettings.asset")
        
        try:
            with open(settings_path, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
                # Find productName: YourProjectName
                match = re.search(r'productName:\s*(.+)', content)
                if match:
                    return match.group(1).strip()
        except Exception as e:
            print(f"Could not read project name: {e}")
        
        # Fallback to folder name
        return os.path.basename(self.project_root)
    
    def build_windows(self):
        """Build for Windows platform"""
        print("\nStarting Windows build...")
        start_time = time.time()
        
        # Build output path using project name
        output_path = os.path.join(self.project_root, "Builds", "Windows", f"{self.project_name}.exe")
        
        cmd = [
            self.unity_path,
            '-batchmode',
            '-quit',
            '-nographics',
            '-projectPath', self.project_root,
            '-executeMethod', 'CommandLineBuild.BuildWindows',
            '-logFile', os.path.join(self.project_root, 'build_windows.log')
        ]
        
        try:
            # Run Unity build command
            result = subprocess.run(cmd, capture_output=True, text=True)
            
            build_time = time.time() - start_time
            
            # Check if build succeeded
            if result.returncode == 0 and os.path.exists(output_path):
                size_mb = os.path.getsize(output_path) / (1024 * 1024)
                print(f"Windows build completed!")
                print(f"   Time: {build_time:.1f} seconds")
                print(f"   Size: {size_mb:.1f} MB")
                print(f"   Output: {output_path}")
                return True
            else:
                print(f"Windows build failed!")
                print(f"Check log file: build_windows.log")
                return False
                
        except Exception as e:
            print(f"Build error: {str(e)}")
            return False

def main():
    """Run the build automation"""
    print("Unity Build Automation - Zero Configuration Edition")
    print("=" * 50)
    
    # Create builder and run
    builder = UnityAutoBuilder()
    builder.build_windows()
    
    print("\nBuild automation complete!")

if __name__ == "__main__":
    main()

Understanding the Code

Key auto-detection features explained:

  1. load_dotenv() - Loads your Unity path from the .env file
  2. find_project_root() - Automatically finds your Unity project by looking for Assets/ProjectSettings folders
  3. Version validation - Compares your project’s Unity version with your executable’s version
  4. Smart error handling - Warns you if Unity versions don’t match before building
  5. get_project_name() - Reads the project name directly from ProjectSettings.asset using regex
  6. re.search() - Regular expressions to find patterns in text (like grep in Unix)
  7. os.path.join() - Cross-platform path handling (works on Windows/Mac/Linux)

The magic is that everything is detected automaticallyβ€”no manual configuration needed!

Run Your First Build

Navigate to your Unity project and run:

cd BuildAutomation
python build.py

The script performs these actions:

  1. Find your Unity project automatically
  2. Read the project name from settings
  3. Build for Windows
  4. Show you exactly where the build was saved

Example output:

Unity Build Automation - Zero Configuration Edition
==================================================
Project: BuildAutomationTest
Root: C:\Projects\SimpleUnityProject
Unity: 2021.3.16f1

Starting Windows build...
Windows build completed!
   Time: 45.2 seconds
   Size: 23.4 MB
   Output: C:\Projects\SimpleUnityProject\Builds\Windows\1.0.0_31-08-2025_14-30\BuildAutomationTest.exe

Build automation complete!

Step 4: Modular Python Architecture

For reliable automation, organize code into modules with this structure:

BuildAutomation/
β”œβ”€β”€ unity_builder/           # Python package
β”‚   β”œβ”€β”€ __init__.py         # Package initialization
β”‚   β”œβ”€β”€ config.py           # Configuration & auto-detection
β”‚   β”œβ”€β”€ platforms.py        # Platform-specific build logic
β”‚   β”œβ”€β”€ reporter.py         # HTML report generation
β”‚   β”œβ”€β”€ builder.py          # Main builder orchestration
β”‚   └── utils.py            # Helper functions
β”œβ”€β”€ build.py                # Simple entry point
β”œβ”€β”€ requirements.txt        # Dependencies
└── .env                    # Unity path configuration

This modular approach makes the code more maintainable and allows for easy extensions.

Software architecture diagram showing unity_builder Python package with four modules (config.py, platforms.py, builder.py, reporter.py) connected by data flow arrows

Step 5: Multi-Platform Build Automation with Rich Output

The enhanced script provides formatted console output using Rich library:

The New Simplified Entry Point

With the modular architecture, build.py becomes beautifully simple:

#!/usr/bin/env python3
"""Unity Build Automation - Main Entry Point"""

import sys
from rich.console import Console
from unity_builder import UnityAutoBuilder
from unity_builder.utils import prompt_build_selection, prompt_custom_platforms

console = Console()

def main():
    """Run Unity build automation with interactive menu."""
    try:
        # Initialize the builder
        builder = UnityAutoBuilder()
        
        # Get user choice
        choice = prompt_build_selection()
        
        if choice == "windows":
            success = builder.build_windows()
            if success:
                console.print("\n[green]Windows build completed successfully![/]")
        
        elif choice == "all":
            results = builder.build_all_platforms()
            builder.generate_report(results)
            console.print("\n[green]Multi-platform build completed![/]")
        
        elif choice == "custom":
            platforms = prompt_custom_platforms()
            results = builder.build_custom_platforms(platforms)
            builder.generate_report(results)
            console.print("\n[green]Custom build completed![/]")
        
    except KeyboardInterrupt:
        console.print("\n\n[yellow]Build cancelled by user.[/]")
        sys.exit(1)

if __name__ == "__main__":
    main()

Beautiful Console Output with Rich

Example console output:

Unity Build Automation - Zero Configuration Edition
══════════════════════════════════════════════════════

Auto-detecting project configuration...

β”Œβ”€ Unity Build Configuration ──────────────────────────┐
β”‚ Project     BuildAutomationTest                   β”‚
β”‚ Root        C:\Projects\SimpleUnityProject        β”‚
β”‚ Company     Angry Shark Studio                    β”‚
β”‚ Version     1.0.0                                 β”‚
β”‚ Unity       2021.3.16f1                          β”‚
β”‚ Bundle ID   com.AngrySharkStudio.BuildTest      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

What would you like to build?
  1. Windows only
  2. All platforms
  3. Custom selection
  4. Exit

Enter your choice (1-4): 2

Starting multi-platform build
Project: BuildAutomationTest v1.0.0

Building for Windows...
Output: Builds/Windows/1.0.0_31-08-2025_14-30/BuildAutomationTest.exe
β ™ Building Windows...

Windows build completed!
   Time: 45.2 seconds
   Size: 23.4 MB
   Version: 1.0.0

Building for macOS...
Skipping macOS: Mac builds only available on macOS

Building for Android...
Output: Builds/Android/1.0.0_31-08-2025_14-30/BuildAutomationTest.apk
β Έ Building Android...

Android build completed!
   Time: 82.1 seconds
   Size: 45.2 MB
   Version: 1.0.0

Building for WebGL...
Note: WebGL builds require significant memory (8GB+ recommended)
Output: Builds/WebGL/1.0.0_31-08-2025_14-30/BuildAutomationTest
⠏ Building WebGL...

WebGL build completed!
   Time: 120.5 seconds
   Size: 15.8 MB
   Version: 1.0.0

Building for iOS...
Skipping iOS: iOS builds only available on macOS (outputs Xcode project)

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   Build Summary                      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Platform β”‚   Status   β”‚   Time   β”‚      Size       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Windows  β”‚ Success    β”‚  45.2s   β”‚    23.4 MB      β”‚
β”‚ macOS    β”‚ Skipped    β”‚   N/A    β”‚      N/A        β”‚
β”‚ Android  β”‚ Success    β”‚  82.1s   β”‚    45.2 MB      β”‚
β”‚ WebGL    β”‚ Success    β”‚  120.5s  β”‚    15.8 MB      β”‚
β”‚ iOS      β”‚ Skipped    β”‚   N/A    β”‚      N/A        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Total platforms: 5
Successful: 3
Total time: 247.8 seconds (4.1 minutes)
Output version: 1.0.0

Build report saved to: BuildAutomation/build_report.html
   (Opened in your default browser)

Multi-platform build completed!

Success screen showing completed Unity builds for Windows, Android, and WebGL with green checkmarks, build times (2m 15s, 3m 42s, 1m 58s) and file sizes

Key Features of the Modular Approach

  1. Clean Separation of Concerns:

    • config.py: Handles all auto-detection
    • platforms.py: Platform-specific build logic
    • reporter.py: HTML report generation
    • utils.py: Common utilities and prompts
  2. Beautiful Console Output:

    • Colored text and emojis
    • Progress indicators during builds
    • Formatted tables for summaries
    • Clear error messages
  3. Version-Based Output:

    • Builds are organized by version
    • Easy to manage multiple releases
    • Clear output structure: Builds/Platform/Version/GameName

Running the Enhanced Build System

cd YourUnityProject/BuildAutomation
python build.py

The script automatically:

  1. Detects your project configuration including version
  2. Shows a beautiful interface with Rich formatting
  3. Builds to version-specific folders
  4. Displays real-time progress with spinners
  5. Generates an enhanced HTML report

Step 6: Build Validation and Error Handling

The modular approach includes complete error handling built into each module:

Built-in Validation Features

The modular system includes complete validation:

  1. Project Validation (in config.py):

    • Verifies Unity project structure
    • Checks for required folders (Assets, ProjectSettings)
    • Validates Unity executable path
    • Auto-detects project settings
  2. Platform Validation (in platforms.py):

    • Checks Android SDK for Android builds
    • Verifies macOS for Mac and iOS builds
    • Warns about memory requirements for WebGL
    • Validates iOS bundle identifier configuration
    • Shows helpful error messages with solutions
  3. Error Reporting (in utils.py and platforms.py):

    • Parses Unity build logs for errors
    • Shows relevant error messages from logs
    • Provides actionable feedback

Example Error Handling

When a build fails, you’ll see helpful output:

Android build failed!
Check log: BuildAutomation/build_android.log

Recent errors from build log:
  Error: Android SDK not found. Please set ANDROID_HOME environment variable
  Error: Minimum API level is 21, current is 19

Troubleshooting Common Issues

Unity Path Not Found

If you get β€œUnity path not found”, check your .env file:

# Make sure .env exists and has the correct path
cat .env

# Should show something like:
UNITY_PATH="C:/Program Files/Unity/Hub/Editor/2021.3.16f1/Editor/Unity.exe"

To find your Unity installation:

  • Windows: Check C:/Program Files/Unity/Hub/Editor/
  • Mac: Check /Applications/Unity/Hub/Editor/
  • Linux: Check wherever you installed Unity Hub

Build Fails Silently

Check the build log files (build_windows.log, etc.) for detailed error messages. Common issues:

  • Missing Android SDK for Android builds
  • Scene not added to Build Settings
  • Script compilation errors

Permission Denied

On Mac/Linux, make Unity executable:

chmod +x /path/to/Unity

Next Steps and Enhancements

The Unity build automation system is now complete. Consider these extensions:

1. Add Build Notifications

Send Discord, Slack, or email notifications when builds complete using webhook integration.

2. Integrate with Version Control

Automatically commit changes and tag releases before building using Git subprocess commands.

3. Schedule Nightly Builds

Use Python’s schedule library or system cron jobs to run builds automatically.

4. Cloud Build Distribution

Upload successful builds to Steam, itch.io, or Google Drive automatically.

Conclusion

This tutorial demonstrated creating a Unity build automation system featuring:

  • Zero-configuration approach - Everything is auto-detected from your Unity project
  • Modular Python architecture - Clean, maintainable code structure
  • Beautiful console output - Rich formatting with colors and progress indicators
  • Version-based organization - Builds organized in version folders
  • Modern Unity practices - TextMeshPro UI and proper C# patterns
  • Complete error handling - Helpful error messages and validation
  • Professional reporting - HTML reports with all build details

The modular approach makes it easy to extend with features like:

  • Parallel builds for faster execution
  • Integration with CI/CD systems
  • Automated uploading to distribution platforms
  • Build notifications via Slack or Discord

Complete Code Repository

Find the complete working example with Unity project at: GitHub: Unity-Python-Build-Automation

The repository includes:

  • Complete Unity sample project
  • Zero-configuration Python scripts
  • .env.example template
  • Detailed setup instructions
  • Troubleshooting guide
  • MIT License for free use in your projects

Frequently Asked Questions (FAQ)

Can I build for all 5 platforms (Windows, Mac, Android, WebGL, iOS) from one machine?

No, platform limitations apply:

  • Windows builds: Can be built on Windows, Mac, or Linux
  • Mac builds: Can only be built on macOS
  • Android builds: Can be built on any platform with Android SDK
  • WebGL builds: Can be built on any platform with sufficient memory
  • iOS builds: Can only be built on macOS (creates Xcode project)

Why does the WebGL build fail with β€œbuild target was unsupported”?

This usually means the WebGL Build Support module isn’t installed. Install it via Unity Hub:

  1. Open Unity Hub
  2. Click the gear icon on your Unity version
  3. Add modules β†’ WebGL Build Support
  4. Restart Unity

The script now includes the -buildTarget WebGL parameter to help Unity load the correct module.

How do I add iOS support to my Unity project?

For iOS builds:

  1. Install iOS Build Support module in Unity Hub
  2. Run the build automation on macOS only
  3. Set a valid bundle identifier in Unity’s Player Settings (not com.Company.ProductName)
  4. The script creates an Xcode project, not a final .ipa file
  5. Open the Xcode project to build and deploy to iOS devices

Can I use this with Unity Cloud Build or CI/CD pipelines?

Yes! Use the command-line interface:

python build_cli.py --all  # Build all platforms
python build_cli.py windows android  # Build specific platforms

Exit codes: 0 for success, 1 for failure - perfect for CI/CD integration.

How do I customize build settings for each platform?

The script uses Unity’s Build Settings for scenes and basic configuration. For custom settings:

  1. Configure platform-specific settings in Unity’s Player Settings
  2. Modify the CommandLineBuild.cs script to add custom build options
  3. Use environment variables or command-line arguments for dynamic configuration

Why organize builds by version and timestamp?

This approach provides:

  • Version tracking: Easy to see which version was built
  • Build history: Multiple builds of the same version don’t overwrite
  • Clean organization: Find builds quickly by platform and version
  • CI/CD friendly: Predictable output paths for automation

What Python version do I need?

Python 3.8 or newer is required. The scripts use:

  • Type hints (3.5+)
  • f-strings (3.6+)
  • Pathlib features (3.8+)

Check your version with: python --version

Can I build without the Rich library for console output?

Yes, but you’ll lose the beautiful formatting. To run without Rich:

  1. Remove Rich imports from the Python files
  2. Replace console.print() with regular print()
  3. Remove progress indicators and tables

The core functionality will still work.

Resources and Further Reading

From Manual to Automated: Your Build Pipeline Evolution

The difference between a hobbyist and a professional Unity developer isn’t just coding skillsβ€”it’s understanding that time spent on automation saves exponentially more time later. Every manual build you eliminate, every error you catch automatically, every platform you can deploy with confidence is an investment in your development velocity.

What you’ve built today isn’t just a build scriptβ€”it’s a foundation for professional Unity development practices:

  • Consistency: Every build follows the same process, eliminating human error
  • Scalability: Add new platforms or team members without multiplying manual work
  • Confidence: Automated validation and reporting means fewer deployment surprises
  • Focus: Spend time on game development, not repetitive build tasks

Best practice: When you find yourself repeating the same Unity task multiple times, consider whether Python automation could streamline the process.

Looking to avoid other Unity development bottlenecks? Check out our guides on Unity MonoBehaviour organization and Unity performance optimization.

This automation system significantly reduces Unity build time and eliminates manual errors. Consider implementing similar automation for other repetitive Unity workflows.


Need Professional Unity Build Automation?

Our Unity Certified Expert team specializes in:

  • Custom Build Pipeline Development - Tailored automation for your specific workflow
  • CI/CD Integration - Jenkins, GitLab, GitHub Actions, TeamCity setup
  • Multi-Platform Optimization - Simultaneous builds with platform-specific settings
  • Enterprise Build Solutions - Scalable automation for large teams

We apply these automation principles across our AR/VR projects to ensure rapid iteration and reliable deployments.

Get expert Unity automation help β†’


Master Unity Development

Join thousands of Unity developers automating their workflows. Get weekly tips on:

  • Build automation strategies
  • Python scripting for Unity
  • CI/CD best practices
  • Performance optimization

Subscribe to our newsletter on the blog β†’


Ready to automate more Unity workflows? Check our Unity tutorials for advanced development techniques.

Angry Shark Studio Logo

About Angry Shark Studio

Angry Shark Studio is a professional Unity AR/VR development studio specializing in mobile multiplatform applications and AI solutions. Our team includes Unity Certified Expert Programmers with extensive experience in AR/VR development.

Related Articles

More Articles

Explore more insights on Unity AR/VR development, mobile apps, and emerging technologies.

View All Articles

Need Help?

Have questions about this article or need assistance with your project?

Get in Touch