How to connect Unity with Flutter?
Creating a Unity and Flutter integration for an app is a great way to combine the strengths of both technologies. Unity is a popular game engine that is used to build high-quality 3D games, while Flutter is a mobile development framework that allows you to build native-looking applications for both iOS and Android. In this blog, we will go over the steps to connect Unity and Flutter for an app.
Get Rashi Saini’s stories in your inbox
Join Medium for free to get updates from this writer.
Step 1: Set up your Unity project
- Start by creating a new Unity project and import any necessary assets, such as 3D models or textures.
Step 2: Create a Unity plugin
- A Unity plugin is a set of code and assets that add functionality to your Unity project. To connect Unity with Flutter, we will create a Unity plugin that will communicate with our Flutter app.
- To create a plugin, go to Assets > Create > Plugins and select “Native Plugin.”
- In the new folder, create a new C# script with the following code:
using System.Runtime.InteropServices;
public class UnityPlugin {
[DllImport("__Internal")]
private static extern void _sendMessageToFlutter(string message);
public static void SendMessageToFlutter(string message) {
_sendMessageToFlutter(message);
}
}Step 3: Build your Unity project for iOS or Android
- To build your Unity project for iOS, go to File > Build Settings and select “iOS.”
- To build your Unity project for Android, go to File > Build Settings and select “Android.”
Step 4: Set up your Flutter project
- Start by creating a new Flutter project and add the “flutter_unity_widget” package.
- In your main.dart file, import the flutter_unity_widget package and add the following code:
import 'package:flutter/material.dart';
import 'package:flutter_unity_widget/flutter_unity_widget.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: UnityExample(),
);
}
}
class UnityExample extends StatefulWidget {
@override
_UnityExampleState createState() => _UnityExampleState();
}
class _UnityExampleState extends State<UnityExample> {
static final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
UnityWidgetController _unityWidgetController;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
body: UnityWidget(
onUnityViewCreated: onUnityCreated,
),
);
}
void onUnityCreated(controller) {
_unityWidgetController = controller;
}
}Step 5: Run your app
- To run your app, go to Run > Run App and select your device.
With these steps, you should now have a working integration between Unity and Flutter for your app. You can now use the UnityPlugin class in your Unity project to send messages to your Flutter app, and use the flutter






