flutter_unity_widget 0.1.6+5 flutter_unity_widget: ^0.1.6+5 copied to clipboard
Flutter Unity 3D widget for embedding Unity game scenes in flutter. This library now supports Unity as a Library.
flutter_unity_widget #
Flutter unity 3D widget for embedding unity in flutter. Now you can make awesome gamified features of your app in Unity and get it rendered in a Flutter app both in fullscreen and embeddable mode. Works great on Android and iOS.
Installation #
First depend on the library by adding this to your packages pubspec.yaml
:
dependencies:
flutter_unity_widget: ^0.1.6+5
Now inside your Dart code you can import it.
import 'package:flutter_unity_widget/flutter_unity_widget.dart';
Preview #
30 fps gifs, showcasing communication between Flutter and Unity:
Setup Project #
For this, there is also a video tutorial, which you can find a here.
Add Unity Project #
- Create an unity project, Example: 'UnityDemoApp'.
- Create a folder named
unity
in flutter project folder. - Move unity project folder to
unity
folder.
Now your project files should look like this.
.
├── android
├── ios
├── lib
├── test
├── unity
│ └── <Your Unity Project> // Example: UnityDemoApp
├── pubspec.yml
├── README.md
Configure Player Settings #
-
First Open Unity Project.
-
Click Menu: File => Build Settings
Be sure you have at least one scene added to your build.
-
=> Player Settings
Android Platform:
-
Make sure your
Graphics APIs
are set to OpenGLES3 with a fallback to OpenGLES2 (no Vulkan) -
Change
Scripting Backend
to IL2CPP. -
Mark the following
Target Architectures
:- ARMv7 ✅
- ARM64 ✅
- x86 ✅
-
iOS Platform:
1. This only works with Unity version >=2019.3 because uses Unity as a library!
2. Depending on where you want to test or run your app, (simulator or physical device), you should select the appropriate SDK on Target SDK
.
Add Unity Build Scripts and Export #
Copy Build.cs
and XCodePostBuild.cs
to unity/<Your Unity Project>/Assets/Scripts/Editor/
Open your unity project in Unity Editor. Now you can export the Unity project with Flutter/Export Android
(for Unity versions up to 2019.2), Flutter/Export Android (Unity 2019.3.*)
(for Unity versions 2019.3 and up, which uses the new Unity as a Library export format), or Flutter/Export IOS
menu.
Android will export unity project to android/UnityExport
.
IOS will export unity project to ios/UnityExport
.
Android Platform Only
- After exporting the unity game, open Android Studio and and add the
Unity Classes
Java.jar
file as a module to the unity project. You just need to do this once if you are exporting from the same version of Unity everytime. The.jar
file is located in the<Your Flutter Project>/android/UnityExport/lib
folder - If using Unity 2019.2 or older, open
build.gradle
ofUnityExport
module and replace the dependencies with
dependencies {
implementation project(':unity-classes') // the unity classes module you added from step 1
}
iOS Platform Only
- open your ios/Runner.xcworkspace (workspace!, not the project) in Xcode and add the exported project in the workspace root (with a right click in the Navigator, not on an item -> Add Files to “Runner” -> add the UnityExport/Unity-Iphone.xcodeproj file
- Select the Unity-iPhone/Data folder and change the Target Membership for Data folder to UnityFramework
- Add this to your Runner/Runner/Runner-Bridging-Header.h
#import "UnityUtils.h"
- Add to AppDelegate.swift before the GeneratePluginRegistrant call:
InitArgs(CommandLine.argc, CommandLine.unsafeArgv)
Or when using Objective-C your main.m
should look like this:
#import "UnityUtils.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
InitArgs(argc, argv);
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
- Opt-in to the embedded views preview by adding a boolean property to the app's
Info.plist
file with the keyio.flutter.embedded_views_preview
and the valueYES
.
AR Foundation (not compatible with Unity 2019.3) #
https://github.com/Unity-Technologies/arfoundation-samples/issues/210
Android only as iOS requires Unity 2019.3.
If you want to use Unity for integrating Augmented Reality in your Flutter app, a few more changes are required:
- Export the Unity Project as previously stated (using the Editor Build script).
- Check if the exported project includes all required Unity libraries (.so) files (
lib/\<architecture\>/libUnityARCore.so
andlibarpresto_api.so
). There seems to be a bug where a Unity export does not include all lib files. If they are missing, use Unity to build a standalone .apk of your AR project, unzip the resulting apk, and copy over the missing .lib files to theUnityExport
module. - Similar to how you've created the
unity-classes
module in Android Studio, create similar modules for all exported .aar and .jar files in theUnityExport/libs
folder (arcore_client.aar
,unityandroidpermissions.aar
,UnityARCore.aar
). - Update the build.gradle script of the
UnityExport
module to depend on the new modules (again, similar to how it depends onunity-classes
). - Finally, update your Dart code build method where you include the
UnityWidget
and addisARScene: true,
. Sadly, this does have the side effect of making your Flutter activity act in full screen, as Unity requires control of your Activity for running in AR, and it makes several modifications to your Activity as a result (including setting it to full screen).
Add UnityMessageManager Support #
Copy UnityMessageManager.cs
to your unity project.
Copy this folder JsonDotNet
to your unity project.
Copy link.xml
to your unity project.
Examples #
Simple Example #
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_unity_widget/flutter_unity_widget.dart';
class UnityDemoScreen extends StatefulWidget {
UnityDemoScreen({Key key}) : super(key: key);
@override
_UnityDemoScreenState createState() => _UnityDemoScreenState();
}
class _UnityDemoScreenState extends State<UnityDemoScreen>{
static final GlobalKey<ScaffoldState> _scaffoldKey =
GlobalKey<ScaffoldState>();
UnityWidgetController _unityWidgetController;
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
body: SafeArea(
bottom: false,
child: WillPopScope(
onWillPop: () {
// Pop the category page if Android back button is pressed.
},
child: Container(
color: colorYellow,
child: UnityWidget(
onUnityViewCreated: onUnityCreated,
),
),
),
),
);
}
// Callback that connects the created controller to the unity controller
void onUnityCreated(controller) {
this._unityWidgetController = controller;
}
}
Communicating with and from Unity #
import 'package:flutter/material.dart';
import 'package:flutter_unity_widget/flutter_unity_widget.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static final GlobalKey<ScaffoldState> _scaffoldKey =
GlobalKey<ScaffoldState>();
UnityWidgetController _unityWidgetController;
double _sliderValue = 0.0;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('Unity Flutter Demo'),
),
body: Card(
margin: const EdgeInsets.all(8),
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Stack(
children: <Widget>[
UnityWidget(
onUnityViewCreated: onUnityCreated,
isARScene: false,
onUnityMessage: onUnityMessage,
),
Positioned(
bottom: 20,
left: 20,
right: 20,
child: Card(
elevation: 10,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 20),
child: Text("Rotation speed:"),
),
Slider(
onChanged: (value) {
setState(() {
_sliderValue = value;
});
setRotationSpeed(value.toString());
},
value: _sliderValue,
min: 0,
max: 20,
),
],
),
),
),
],
),
),
),
);
}
// Communcation from Flutter to Unity
void setRotationSpeed(String speed) {
_unityWidgetController.postMessage(
'Cube',
'SetRotationSpeed',
speed,
);
}
// Communication from Unity to Flutter
void onUnityMessage(controller, message) {
print('Received message from unity: ${message.toString()}');
}
// Callback that connects the created controller to the unity controller
void onUnityCreated(controller) {
this._unityWidgetController = controller;
}
}
API #
pause()
(Use this to pause unity player)resume()
(Use this to resume unity player)postMessage(String gameObject, methodName, message)
(Allows you invoke commands in Unity from flutter)onUnityMessage(data)
(Unity to flutter bindding and listener)
Known issues #
- Android Export requires several manual changes
- Using AR will make the activity run in full screen (hiding status and navigation bar).
Contributors ✨ #
Thanks goes to these wonderful people (emoji key):
Rex Raphael 💻 📖 💬 🐛 👀 ✅ |
Thomas Stockx 💻 📖 💬 ✅ |
Kris Pypen 💻 📖 💬 ✅ |
Lorant Csonka 📖 📹 |
This project follows the all-contributors specification. Contributions of any kind welcome!