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, ipad os and ios. there are now two unity app examples in the unity folder, one with the default scene and another based on unity ar foundation samples.
note: supports only unity 2019.4.3 or later. unityframework does not support emulator.
installation
first depend on the library by adding this to your packages pubspec.yaml
:
dependencies:
flutter_unity_widget: ^4.1.0
null-safe version:
dependencies:
flutter_unity_widget: ^4.2.1
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
for this, there is also a video tutorial, which you can find a here.
in the tutorial below, there are steps specific to each platform, denoted by a :information_source: icon followed by
the platform name (android or ios). you can click on its icon to expand it.
prerequisites
- an existing flutter project (if there is none, you can create a new one)
- an existing unity project (if there is none, you can create a new one).
- a
flutterunitypackage.unitypackage
file (you can access the unity packages in the scripts folder too)
steps
- create a folder named unity and move the unity project into there.
the expected path is unity/project-name/…
- copy the flutterunitypackage.unitypackage file into the unity project folder.
the expected path is unity/project-name/flutterunitypackage.unitypackage
- using unity, open the unity project, go to file > build settings > player settings
and change the following under the configuration section:
- in scripting backend, change to il2cpp
- in target architectures, select armv7 and arm64
:information_source: ios
select the appropriate sdk on target sdk depending on where you want to test or run your app (simulator or physical device).
be sure you have at least one scene added to your build.
- go to assets > import package > custom package and select the
flutterunitypackage.unitypackage file. click on import. - after importing, click on flutter and select the export android option (will export to android/unitylibrary) or the export ios
option (will export to ios/unitylibrary).
do not use flutter > export platform plugin as it was specially added to work with
flutter_unity_cli
for larger projects.
:information_source: android
the export script automatically sets things up for you, so you don’t have to do anything for android. but if you want to manually set it up, continue.
6.1. open the android/settings.gradle file and change the following:
+ include ":unitylibrary"
+ project(":unitylibrary").projectdir = file("./unitylibrary")
6.2. open the android/app/build.gradle file and change the following:
dependencies {
+ implementation project(':unitylibrary')
}
6.3. if you need to build a release package, open the android/app/build.gradle file and change the following:
buildtypes {
release {
signingconfig signingconfigs.debug
}
+ debug {
+ signingconfig signingconfigs.debug
+ }
+ profile {
+ signingconfig signingconfigs.debug
+ }
+ innertest {
+ matchingfallbacks = ['debug', 'release']
+ }
+ }
the code above use the
debug
signconfig for all buildtypes, which can be changed as you well if you need specify signconfig.
6.4. if you use minifyenabled true
in your android/app/build.gradle file, open the android/unitylibrary/proguard-unity.txt and change the following:
+ -keep class com.xraph.plugin.** {*;}
6.5. if you want unity in it’s own activity as an alternative, open the android/app/src/main/androidmanifest.xml and change the following:
+ <activity
+ android:name="com.xraph.plugin.flutter_unity_widget.overrideunityactivity"
+ android:theme="@style/unitythemeselector"
+ android:screenorientation="fullsensor"
+ android:launchmode="singletask"
+ android:configchanges="mcc|mnc|locale|touchscreen|keyboard|keyboardhidden|navigation|orientation|screenlayout|uimode|screensize|smallestscreensize|fontscale|layoutdirection|density"
+ android:hardwareaccelerated="false"
+ android:process=":unity">
+ <meta-data android:name="com.xraph.plugin.flutter_unity_widget.overrideunityactivity" android:value="true" />
+ </activity>
:information_source: ios
6.1. open the ios/runner.xcworkspace (workspace, not the project) file in xcode, right-click on the navigator (not on an item), go to add files to “runner” and add
the ios/unitylibrary/unity-iphone.xcodeproj file.
6.2. (optional) select the unity-iphone/data folder and change the target membership for data folder to unityframework.
6.3.1. if you’re using swift, open the ios/runner/appdelegate.swift file and change the following:
import uikit
import flutter
+ import flutter_unity_widget
@uiapplicationmain
@objc class appdelegate: flutterappdelegate {
override func application(
_ application: uiapplication,
didfinishlaunchingwithoptions launchoptions: [uiapplication.launchoptionskey: any]?
) -> bool {
+ initunityintegrationwithoptions(argc: commandline.argc, argv: commandline.unsafeargv, launchoptions)
generatedpluginregistrant.register(with: self)
return super.application(application, didfinishlaunchingwithoptions: launchoptions)
}
}
6.3.2. if you’re using objective-c, open the ios/runner/main.m file and change the following:
+ #import "flutter_unity_widget.swift.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
+ initunityintegration(argc, argv);
return uiapplicationmain(argc, argv, nil, nsstringfromclass([appdelegate class]));
}
}
6.4. open the ios/runner/info.plist and change the following:
<dict>
+ <key>io.flutter.embedded_views_preview</key>
+ <string>yes</string>
</dict>
6.5. add the unityframework.framework file as a library to the runner project.
setup ar foundation
check out the unity ar foundation samples in the demo repository.
this repository is not guaranteed to be up-to-date with the latestflutter-unity-view-widget
master. make sure to follow
the steps listed below for setting up ar foundation on ios and android in your project.
:information_source: android
- open the lib/architecture/ folder and check if there are both libunityarcore.so and libarpresto_api.so files.
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 theunitylibrary
module. - repeat steps 6.1 and 6.2 for android, replacing
unitylibrary
witharcore_client
,unityandroidpermissions
andunityarcore
. - when using
unitywidget
in flutter, setfullscreen: false
to disable fullscreen.
:information_source: ios
- open the ios/runner/info.plist and change the following:
<dict>
+ <key>privacy - camera usage description</key>
+ <string>$(product_name) uses cameras</string>
</dict>
setup vuforia
thanks to @piotrxkolasinski for writing down the exact steps:
- open the android/unitylibrary/build.gradle file and change the following:
- implementation(name: 'vuforiawrapper', ext: 'aar')
+ implementation project(':vuforiawrapper')
- using android studio, go to file > open and select the android/ folder. a
new project will open.
don’t worry if the error message “project with path ‘:vuforiawrapper’ could not be
found in project ‘:unitylibrary'” appears. the next step will fix it.
- in this new project window, go to file > new > new module > import .jar/.aar package
and select the android/unitylibrary/libs/vuforiawrapper.aar file. a new folder
named vuforiawrapper will be created inside android/. you can now close this
new project window.
communicating
flutter-unity
- on a
unitywidget
widget, get theunitywidgetcontroller
received by theonunitycreated
callback. - use the method
postmessage
to send a string, using the gameobject name and the name of a behaviour method that should be called.
unity-flutter
- select the gameobject that should execute the communication and go to inspector > add component > unity message manager.
- create a new
monobehaviour
subclass and add to the same gameobject as a script. - on this new behaviour, call
getcomponent<unitymessagemanager>()
to get aunitymessagemanager
. - use the method
sendmessagetoflutter
to send a string. receive this message using theonunitymessage
callback of aunitywidget
.
troubleshooting
location: unity
error:
invalidoperationexception: the build target does not support build appending.
solution:
- open the unity/project-name/assets/flutterunityintegration/editor/build.cs file.
1.1. on line 48, change the following:
- var options = buildoptions.acceptexternalmodificationstoplayer;
+ var options = buildoptions.allowdebugging;
+ editoruserbuildsettings.exportasgoogleandroidproject = true;
1.2. on line 115, change the following:
- var options = buildoptions.acceptexternalmodificationstoplayer;
+ var options = buildoptions.allowdebugging;
location: android studio
error:
minsdkversion xx cannot be smaller than version 19 declared in library
[:flutter_unity_widget] .../androidmanifest.xml as the library might be using
apis not available in xx
solution:
- open the android/app/build.gradle file and change the following:
- minsdkversion xx
+ minsdkversion 19
location: android studio
error:
e: .../flutterunitywidgetbuilder.kt: (15, 42): expecting a parameter declaration
e: .../flutterunitywidgetbuilder.kt: (23, 25): expecting an argument
e: .../flutterunitywidgetcontroller.kt: (22, 44): expecting a parameter declaration
e: .../flutterunitywidgetfactory.kt: (13, 58): expecting a parameter declaration
solution:
- open the android/build.gradle file and change the following:
- ext.kotlin_version = '1.3.50'
+ ext.kotlin_version = '1.4.31'
location: android studio
error:
unable to find a matching variant of project :unitylibrary:
solution:
- open the android/app/build.gradle file and change the following:
lintoptions {
disable 'invalidpackage'
+ checkreleasebuilds false
}
examples
simple example
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_unity_widget/flutter_unity_widget.dart';
void main() {
runapp(materialapp(
home: unitydemoscreen()
));
}
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(
onunitycreated: 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(
onunitycreated: onunitycreated,
onunitymessage: onunitymessage,
onunitysceneloaded: onunitysceneloaded,
fullscreen: false,
),
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(message) {
print('received message from unity: ${message.tostring()}');
}
// callback that connects the created controller to the unity controller
void onunitycreated(controller) {
this._unitywidgetcontroller = controller;
}
// communication from unity when new scene is loaded to flutter
void onunitysceneloaded(sceneloaded sceneinfo) {
print('received scene loaded from unity: ${sceneinfo.name}');
print('received scene loaded from unity buildindex: ${sceneinfo.buildindex}');
}
}
props
fullscreen
(enable or disable fullscreen mode on android)
api
pause()
(use this to pause unity player)resume()
(use this to resume unity player)unload()
(use this to unload unity player) *requires unity 2019.4.3 or laterquit()
(use this to quit unity player)postmessage(string gameobject, methodname, message)
(allows you invoke commands in unity from flutter)onunitymessage(data)
(unity to flutter binding and listener)onunityunloaded()
(unity to flutter listener when unity is unloaded)onunitysceneloaded(string name, int buildindex, bool isloaded, bool isvalid,)
(unity to flutter binding and listener when new scene is loaded)
known issues
- remember to disabled fullscreen in unity player settings to disable unity fullscreen.
- project fails to build due to some native dependencies in your unity project, please integrate the native libraries for those dependencies on android or ios
- app crashes on screen exit and re-entry do this
build setting – ios – other settings – configuration – enable custom background behaviors
Comments are closed.