Skip to content

How to Embed Unity Games in Flutter Apps with flutter_unity_widget

How to Embed Unity Games in Flutter Apps with flutter_unity_widget

Are you looking to add interactive 3D content or games to your Flutter app? The flutter_unity_widget package allows you to easily embed Unity scenes and games directly into your Flutter applications. In this guide, we’ll explore how to set up and use flutter_unity_widget to create engaging cross-platform experiences.

What is flutter_unity_widget?

flutter_unity_widget is a Flutter plugin that enables embedding Unity game scenes within Flutter apps. It supports Android, iOS, and web platforms, allowing you to leverage Unity’s powerful 3D capabilities alongside Flutter’s versatile UI toolkit.

Key features include:

  • Embed Unity scenes as Flutter widgets
  • Two-way communication between Flutter and Unity
  • Support for multiple Unity instances
  • Lifecycle management (pause, resume, etc.)

Setting Up Your Project

To get started with flutter_unity_widget, you’ll need both a Flutter project and a Unity project. Here’s how to set things up:

  1. Add the dependency to your pubspec.yaml:
dependencies:
  flutter_unity_widget: ^2022.2.1
  1. Create a unity folder in your Flutter project root and place your Unity project inside it.

  2. In your Unity project, import the latest fuw-XXXX.unitypackage from the flutter_unity_widget repository.

  3. Configure your Unity build settings:

    • Set Scripting Backend to IL2CPP
    • For Android, select ARMv7 and ARM64 architectures
    • For iOS, choose the appropriate Target SDK
  4. Export your Unity project:

    • For Android: Flutter > Export Android
    • For iOS: Flutter > Export iOS
  5. Make platform-specific adjustments as needed (see the official documentation for details).

Using flutter_unity_widget in Your App

Now that your project is set up, let’s look at how to use flutter_unity_widget in your Flutter app.

Basic Usage

Here’s a simple example of embedding a Unity widget in your Flutter app:

import 'package:flutter/material.dart';
import 'package:flutter_unity_widget/flutter_unity_widget.dart';

class UnityDemoScreen extends StatefulWidget {
  @override
  _UnityDemoScreenState createState() => _UnityDemoScreenState();
}

class _UnityDemoScreenState extends State<UnityDemoScreen> {
  UnityWidgetController? _unityWidgetController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Unity in Flutter')),
      body: UnityWidget(
        onUnityCreated: onUnityCreated,
      ),
    );
  }

  void onUnityCreated(controller) {
    _unityWidgetController = controller;
  }
}

This code creates a full-screen Unity widget within a Flutter scaffold. The onUnityCreated callback provides a controller for interacting with the Unity instance.

Communication Between Flutter and Unity

One of the most powerful features of flutter_unity_widget is the ability to send messages between Flutter and Unity. Here’s how you can implement two-way communication:

// Send a message from Flutter to Unity
_unityWidgetController?.postMessage(
  'GameManager',
  'SetScore',
  '100',
);

// Listen for messages from Unity in Flutter
UnityWidget(
  onUnityMessage: (message) {
    print('Message from Unity: $message');
  },
  // ... other properties
)

In your Unity C# script:

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public void SetScore(string score)
    {
        Debug.Log($"Score set to: {score}");
    }

    public void SendMessageToFlutter()
    {
        UnityMessageManager.Instance.SendMessageToFlutter("Hello from Unity!");
    }
}

This allows you to trigger Unity functions from Flutter and send data back to your Flutter app from Unity.

A Simple Project: Interactive 3D Cube

Let’s create a simple project that demonstrates the integration of Unity and Flutter. We’ll make an interactive 3D cube that can be rotated using a slider in the Flutter UI.

  1. In Unity, create a new scene with a cube at the center.
  2. Attach the following script to the cube:
using UnityEngine;

public class CubeRotator : MonoBehaviour
{
    private float rotationSpeed = 10f;

    void Update()
    {
        transform.Rotate(Vector3.up, rotationSpeed * Time.deltaTime);
    }

    public void SetRotationSpeed(string speed)
    {
        rotationSpeed = float.Parse(speed);
    }
}
  1. In your Flutter app, create a new screen with a UnityWidget and a slider:
import 'package:flutter/material.dart';
import 'package:flutter_unity_widget/flutter_unity_widget.dart';

class CubeDemoScreen extends StatefulWidget {
  @override
  _CubeDemoScreenState createState() => _CubeDemoScreenState();
}

class _CubeDemoScreenState extends State<CubeDemoScreen> {
  UnityWidgetController? _unityWidgetController;
  double _sliderValue = 10.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('3D Cube Demo')),
      body: Column(
        children: [
          Expanded(
            child: UnityWidget(
              onUnityCreated: (controller) {
                _unityWidgetController = controller;
              },
            ),
          ),
          Padding(
            padding: EdgeInsets.all(8.0),
            child: Row(
              children: [
                Text('Rotation Speed:'),
                Expanded(
                  child: Slider(
                    value: _sliderValue,
                    min: 0,
                    max: 100,
                    onChanged: (value) {
                      setState(() {
                        _sliderValue = value;
                      });
                      _unityWidgetController?.postMessage(
                        'Cube',
                        'SetRotationSpeed',
                        value.toString(),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

This example creates a Flutter screen with a Unity widget showing the 3D cube and a slider to control its rotation speed. The slider value is sent to Unity using the postMessage method, updating the cube’s rotation in real-time.

Conclusion

The flutter_unity_widget package opens up exciting possibilities for creating rich, interactive experiences in Flutter apps. By combining Unity’s 3D capabilities with Flutter’s UI toolkit, you can build engaging applications that stand out from the crowd.

Remember to check out the official flutter_unity_widget documentation for more advanced features and troubleshooting tips. Happy coding!


Related Articles

External Resources

Leave a Reply

Your email address will not be published. Required fields are marked *