Game Framework

Quick Start

This guide will walk you through creating a Flutter app with Unity integration using Game Framework. In just 10 minutes, you'll have a working app with 3D game content running in Flutter!

This tutorial uses Unity, but the process is similar for Unreal Engine. Just replace unity with unreal in the commands.

Prerequisites

Before starting, ensure you have:

Step-by-Step Tutorial

Create a New Flutter Project

First, create a new Flutter application:

flutter create my_game_app
cd my_game_app

Add Game Framework dependencies to pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  gameframework: ^0.0.1
  gameframework_unity: ^0.0.1

Install the packages:

flutter pub get

Add Unity to Your Project

Use the game add engine command to create a Unity project in your Flutter app:

game add engine unity

This will:

  • Create a unity_project/ directory with a sample Unity project
  • Generate a .game.yml configuration file
  • Set up the Unity project with Game Framework scripts

The command automatically downloads the latest Unity plugin scripts if they're not found locally!

Initialize the SDK

Update your lib/main.dart to initialize Game Framework:

import 'package:flutter/material.dart';
import 'package:gameframework/gameframework.dart';
import 'package:gameframework_unity/gameframework_unity.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize Unity plugin
  UnityEnginePlugin.initialize();
  
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Game App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const GameScreen(),
    );
  }
}

class GameScreen extends StatefulWidget {
  const GameScreen({super.key});

  @override
  State<GameScreen> createState() => _GameScreenState();
}

class _GameScreenState extends State<GameScreen> {
  GameEngineController? _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Unity in Flutter'),
      ),
      body: GameWidget(
        engineType: GameEngineType.unity,
        config: const GameEngineConfig(
          runImmediately: true,
        ),
        onEngineCreated: (controller) {
          setState(() {
            _controller = controller;
          });
          print('Unity engine created!');
        },
        onMessage: (message) {
          print('Message from Unity: ${message.data}');
        },
      ),
      floatingActionButton: _controller != null
          ? FloatingActionButton(
              onPressed: () {
                // Send message to Unity
                _controller!.sendMessage(
                  'GameManager',
                  'RotateCube',
                  '360',
                );
              },
              child: const Icon(Icons.rotate_right),
            )
          : null,
    );
  }
}

Export the Unity Project

Export your Unity game for the target platform:

# For Android
game export unity --platform android

# For iOS (macOS only)
game export unity --platform ios

# For both platforms
game export unity --platform android,ios

This command:

  • Opens Unity in batch mode
  • Builds the game for specified platforms
  • Saves exports to the configured export path

The first export may take a few minutes as Unity compiles the project.

Sync Files to Flutter

Sync the exported Unity files to your Flutter project:

# For Android
game sync unity --platform android

# For iOS
game sync unity --platform ios

# For both platforms
game sync unity --platform android,ios

This copies:

  • Android: unityLibrary folder to android/
  • iOS: UnityFramework.framework to ios/

Run Your App

Now you can run your Flutter app with Unity integrated!

# Run on Android device/emulator
flutter run -d android

# Run on iOS device/simulator (macOS only)
flutter run -d ios

# Run on desktop (beta)
flutter run -d macos

You should see:

  • Your Flutter UI with an AppBar and FloatingActionButton
  • Unity rendering a 3D scene in the center
  • Tapping the button sends a message to Unity

Congratulations! You've successfully integrated Unity into a Flutter app!

What You've Learned

In this quick start, you've:

  1. ✅ Created a Flutter project with Game Framework
  2. ✅ Added a Unity project using the CLI
  3. ✅ Initialized the Unity plugin in your Flutter app
  4. ✅ Created a GameWidget to display Unity content
  5. ✅ Exported and synced Unity builds
  6. ✅ Sent messages from Flutter to Unity

Next Steps

Now that you have the basics working, explore more advanced features:

Communication

Learn about bidirectional messaging:

Advanced Features

CLI Workflows

Streamline your development:

Platform-Specific Guides

Common Next Tasks

Customize the Unity Scene

Open unity_project/ in Unity Editor and:

  1. Modify the sample scene
  2. Add your own game objects
  3. Create C# scripts that communicate with Flutter
  4. Re-export and sync

Add More UI

Enhance your Flutter UI:

  • Add buttons to control the game
  • Display game state in Flutter widgets
  • Create Flutter overlays on top of Unity

Handle Game Events

Listen for events from Unity:

onMessage: (message) {
  if (message.target == 'Flutter') {
    // Handle messages sent to Flutter
    switch (message.method) {
      case 'GameOver':
        _showGameOverDialog(message.data);
        break;
      case 'ScoreUpdated':
        _updateScore(message.data);
        break;
    }
  }
}

Troubleshooting

Unity Not Found

If the CLI can't find Unity:

# Check Unity installation
which unity

# Specify Unity path in .game.yml
engines:
  unity:
    project_path: ./unity_project
    unity_path: /Applications/Unity/Hub/Editor/2022.3.0f1/Unity.app

Export Failed

Common export issues:

  • Unity project doesn't compile: Fix errors in Unity Editor first
  • Scenes not included: Check Build Settings in Unity
  • Platform not installed: Install Android/iOS build support in Unity Hub

Sync Failed

If sync fails:

  • Ensure export completed successfully
  • Check .game.yml configuration paths
  • Verify export directory exists

App Crashes

Common crash causes:

  • Missing framework: Ensure sync completed for your platform
  • Plugin not initialized: Call UnityEnginePlugin.initialize() in main()
  • Platform mismatch: Export and run on the same platform

For more troubleshooting help, see the Troubleshooting Guide.

Alternative: Use Scaffold Command

For a quicker start, use the scaffold command to create a complete package:

game scaffold --name my_game --engine unity

This creates:

  • Complete Flutter plugin package structure
  • Unity project with sample game
  • Example app ready to run
  • Pre-configured .game.yml

See the Scaffold Command documentation for details.

Getting Help

Need assistance?