Embeddable unity game engine view for Flutter.

Overview

flutter_unity_widget

All Contributors

version MIT License PRs Welcome

Watch on GitHub Star on GitHub

Gitter

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.

Notice

I am encumbered, need me to respond tag me Rex Isaac Raphael

This plugin expects you to atleast know how to use Unity Engine. If you have issues with how unity widget is presented, you can please modify your unity project build settings as you seem fit.

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.2

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:

gif gif


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 ℹ️ icon followed by the platform name (Android or iOS). You can click on its icon to expand it.

Prerequisites

NDK

If your project requires Android NDK, you have to setup following:

Your android project needs to know the path of the NDK Unity uses. You can find the path to the NDK under Preferences -> External Tools:

NDK Path

Copy the path by right click and paste the path here in your android/local.properties:

    ndk.dir=/Applications/Unity/Hub/Editor/2020.3.19f1/PlaybackEngines/AndroidPlayer/NDK

That's it! You don't need to tell your Android App in your app/build.gradle the NDK version or other NDK settings. It's all connected to Unity now.

Steps

  1. Create a folder named unity and move the Unity project into there.

The expected path is unity/project-name/...

  1. Copy the FlutterUnityPackage.unitypackage file into the Unity project folder.

The expected path is unity/project-name/FlutterUnityPackage.unitypackage

  1. 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

ℹ️ 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.

  1. Go to Assets > Import Package > Custom Package and select the FlutterUnityPackage.unitypackage file. Click on Import.

  2. 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.

ℹ️ 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:

+ + ">
+    
    
+        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">
+    
    
+    
ℹ️ 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:

     

    +        
     
      io.flutter.embedded_views_preview
     

    +        
     
      YES
     
     
   

6.5. Add the UnityFramework.framework file as a library to the Runner project.

Setup AR Foundation

gif

Check out the Unity AR Foundation samples in the demo repository. This repository is not guaranteed to be up-to-date with the latest flutter-unity-view-widget master. Make sure to follow the steps listed below for setting up AR Foundation on iOS and Android in your project.

ℹ️ Android
  1. 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 the unityLibrary module.

  2. Repeat steps 6.1 and 6.2 for Android, replacing unityLibrary with arcore_client, unityandroidpermissions and UnityARCore.

  3. When using UnityWidget in Flutter, set fullscreen: false to disable fullscreen.

ℹ️ iOS
  1. Open the ios/Runner/Info.plist and change the following:
     

    +        
     
      Privacy - Camera Usage Description
     

    +        
     
      $(PRODUCT_NAME) uses Cameras
     
     
   

Setup Vuforia

Thanks to @PiotrxKolasinski for writing down the exact steps:

  1. Open the android/unityLibrary/build.gradle file and change the following:
-    implementation(name: 'VuforiaWrapper', ext: 'aar')
+    implementation project(':VuforiaWrapper')
  1. 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.

  1. 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

  1. On a UnityWidget widget, get the UnityWidgetController received by the onUnityCreated callback.

  2. 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

  1. Select the GameObject that should execute the communication and go to Inspector > Add Component > Unity Message Manager.

  1. Create a new MonoBehaviour subclass and add to the same GameObject as a script.

  2. On this new behaviour, call GetComponent () to get a UnityMessageManager.

  3. Use the method SendMessageToFlutter to send a string. Receive this message using the onUnityMessage callback of a UnityWidget.

Troubleshooting

Location: Unity

Error:

InvalidOperationException: The build target does not support build appending.

Solution:

  1. 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:

  1. 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:

  1. 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:

  1. 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 later
  • quit() (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

Sponsors

Support this project with your organization. Your donations will be used to help children first and then those in need. Your logo will show up here with a link to your website. [Contribute]

Contributors

Thanks goes to these wonderful people (emoji key):

Rex Raphael
Rex Raphael

💻 📖 💬 🐛 👀
Thomas Stockx
Thomas Stockx

💻 📖 💬
Kris Pypen
Kris Pypen

💻 📖 💬
Lorant Csonka
Lorant Csonka

📖 📹

This project follows the all-contributors specification. Contributions of any kind welcome!

Comments
  • Closing unity screen and relaunching it crashes the app

    Closing unity screen and relaunching it crashes the app

    The unity app run the first time i launch the screen, if I navigate back and reopen the app crashes.

    steps: 1- opening unity screen and unity project is running fine. 2- navigate back, this exception is shown: E/flutter ( 7701): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: MissingPluginException(No implementation found for method dispose on channel unity_view_0) E/flutter ( 7701): #0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:314:7) E/flutter ( 7701): <asynchronous suspension> E/flutter ( 7701): #1 UnityWidgetController._dispose (package:flutter_unity_widget/flutter_unity_widget.dart:55:19) E/flutter ( 7701): <asynchronous suspension> E/flutter ( 7701): #2 _UnityWidgetState.dispose (package:flutter_unity_widget/flutter_unity_widget.dart:103:19) E/flutter ( 7701): #3 StatefulElement.unmount (package:flutter/src/widgets/framework.dart:4107:12) E/flutter ( 7701): #4 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1737:13) E/flutter ( 7701): #5 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #6 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3955:14) E/flutter ( 7701): #7 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #8 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #9 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3955:14) E/flutter ( 7701): #10 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #11 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #12 MultiChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:5181:16) E/flutter ( 7701): #13 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #14 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #15 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3955:14) E/flutter ( 7701): #16 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #17 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #18 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3955:14) E/flutter ( 7701): #19 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #20 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #21 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3955:14) E/flutter ( 7701): #22 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #23 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #24 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:5080:14) E/flutter ( 7701): #25 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #26 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #27 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3955:14) E/flutter ( 7701): #28 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #29 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #30 SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:5080:14) E/flutter ( 7701): #31 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #32 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #33 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3955:14) E/flutter ( 7701): #34 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #35 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #36 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:3955:14) E/flutter ( 7701): #37 _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:1733:13) E/flutter ( 7701): #38 _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:1735:7) E/flutter ( 7701): #39 ComponentElement.visitChildren

    3- reopen the screen again the app crashes with the following error

    E/zygote64( 7701): No implementation found for void com.unity3d.player.UnityPlayer.nativeRestartActivityIndicator() (tried Java_com_unity3d_player_UnityPlayer_nativeRestartActivityIndicator and Java_com_unity3d_player_UnityPlayer_nativeRestartActivityIndicator__) E/flutter ( 7701): [ERROR:flutter/shell/platform/android/platform_view_android_jni.cc(40)] java.lang.UnsatisfiedLinkError: No implementation found for void com.unity3d.player.UnityPlayer.nativeRestartActivityIndicator() (tried Java_com_unity3d_player_UnityPlayer_nativeRestartActivityIndicator and Java_com_unity3d_player_UnityPlayer_nativeRestartActivityIndicator__) E/flutter ( 7701): at com.unity3d.player.UnityPlayer.nativeRestartActivityIndicator(Native Method) E/flutter ( 7701): at com.unity3d.player.UnityPlayer.resume(Unknown Source:27) E/flutter ( 7701): at com.rexraphael.flutterunitywidget.UnityUtils.addUnityViewToGroup(UnityUtils.java:141) E/flutter ( 7701): at com.rexraphael.flutterunitywidget.UnityView.setUnityPlayer(UnityView.java:21) E/flutter ( 7701): at com.rexraphael.flutterunitywidget.FlutterUnityView.getUnityView(FlutterUnityView.java:101) E/flutter ( 7701): at com.rexraphael.flutterunitywidget.FlutterUnityView.<init>(FlutterUnityView.java:30) E/flutter ( 7701): at com.rexraphael.flutterunitywidget.FlutterUnityViewFactory.create(FlutterUnityViewFactory.java:34) E/flutter ( 7701): at io.flutter.plugin.platform.SingleViewPresentation.onCreate(SingleViewPresentation.java:154) E/flutter ( 7701): at android.app.Dialog.dispatchOnCreate(Dialog.java:403) E/flutter ( 7701): at android.app.Dialog.show(Dialog.java:302) E/flutter ( 7701): at android.app.Presentation.show(Presentation.java:249) E/flutter ( 7701): at io.flutter.plugin.platform.VirtualDisplayController.<init>(VirtualDisplayController.java:92) E/flutter ( 7701): at io.flutter.plugin.platform.VirtualDisplayController.create(VirtualDisplayController.java:52) E/flutter ( 7701): at io.flutter.plugin.platform.PlatformViewsController$1.createPlatformView(PlatformViewsController.java:97) E/flutter ( 7701): at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.create(PlatformViewsChannel.java:87) E/flutter ( 7701): at io.flutter.embedding.engine.systemchannels.PlatformViewsChannel$1.onMethodCall(PlatformViewsChannel.java:51) E/flutter ( 7701): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222) E/flutter ( 7701): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96) E/flutter ( 7701): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:643) E/flutter ( 7701): at android.os.MessageQueue.nativePollOnce(Native Method) E/flutter ( 7701): at android.os.MessageQueue.next(MessageQueue.java:331) E/flutter ( 7701): at android.os.Looper.loop(Looper.java:147) E/flutter ( 7701): at android.app.ActivityThread.main(ActivityThread.java:6699) E/flutter ( 7701): at java.lang.reflect.Method.invoke(Native Method) E/flutter ( 7701): at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:246) E/flutter ( 7701): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783) E/flutter ( 7701): F/flutter ( 7701): [FATAL:flutter/shell/platform/android/platform_view_android_jni.cc(77)] Check failed: CheckException(env). Lost connection to device.

    how can successfully handle disposing and launching unity?

    bug android 
    opened by TarekMedhat 43
  • Failed to build iOS version - No such module 'UnityFramework'

    Failed to build iOS version - No such module 'UnityFramework'

    Hello,

    I'm using the latest (4.0.2) package version and I'm struggling to build an iOS version for simulator using XCode for both, your DemoApp example and my custom Unity app. I've configured XCode according to the iOS setup description in README.md.

    The error for Debug mode:

    flutter-unity-view-widget/ios/Classes/FLTUnityView.swift:10:8: No such module 'UnityFramework'

    The error for Release mode:

    flutter-unity-view-widget/example/ios/Runner/AppDelegate.swift:3:8: No such module 'flutter_unity_widget'

    flutter --version
    Flutter 2.0.4 • channel stable • https://github.com/flutter/flutter.git
    Framework • revision b1395592de (3 days ago) • 2021-04-01 14:25:01 -0700
    Engine • revision 2dce47073a
    Tools • Dart 2.12.2
    

    Could you please help? What am I doing wrong?

    opened by ilicmilan 41
  • iOS compile fails

    iOS compile fails

    When I compile the code I receive the following error:

    /{personalpath}/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_unity_widget-0.1.6+2/ios/Classes/UnityUtils.mm:55:10: error: no visible @interface for 'UnityFramework' declares the selector 'frameworkWarmup:argv:'
            [ufw frameworkWarmup: g_argc argv: g_argv];
             ~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
        1 error generated.
    

    My edited files are as follows: Runner-Bridging-Header.h

    #import "GeneratedPluginRegistrant.h"
    #import "UnityUtils.h"
    

    AppDelegate.swift

    import UIKit
    import Flutter
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
      ) -> Bool {
        InitArgs(CommandLine.argc, CommandLine.unsafeArgv)
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }
    
    
    ios 
    opened by rafbanaan 31
  • Problem on ios when exit from screen and enter again

    Problem on ios when exit from screen and enter again

    Hi I'm having a problem that is not present on android, only on ios devices.

    When the user exits (pop) the flutter screen where I have embeded the unity view this error pops up on the debug console

    Unhandled Exception: MissingPluginException(No implementation found for method dispose on channel unity_view_0)

    But everything apparently is working normal on flutter side, but the problem happens when the user enters for a second time where the flutter screen where the unity is embeded. If the user choose to exit again unity view flutter doesn't pop the screen.

    The only tip that I have is that error that I mention first. Other user mention this same error before #107 and it was close because it @juicycleff mention that was fixed but this error still happens on the last version of the plugin.

    So anyone has any idea on how to resolve this issue?

    opened by Darkmax 30
  • Android Unity 2020.x freeze

    Android Unity 2020.x freeze

    Info: When i use Flutter Export with 2020.x.x it exports with the size of 90 KB version of unity-classes.jar. But when i export with 2019 it exports with the 100 KB version of unity-classes.jar which located in android/unityLibrary/libs/

    Bug On 2020 build : After i build flutter. Unity starts fine with no problems. But when i remove Unity from screen and after when i call unity back, Unity totally freezes. Cant solve. Only solution i found manually changing unity-classes with 2019's unity-classes . It solves the problem but i think its not a good solution. any help,solution will be great.

    Thank you. :)

    opened by sevantasci 29
  • [Bug] Unity rendering beneath flutter on Android 7 device.

    [Bug] Unity rendering beneath flutter on Android 7 device.

    Describe the bug The flutter-unity-widget 3.0.0 example works fine on most devices I tested with, but it runs into an issue on my budget android 7 testing device. I don't have any other devices running old android versions like this, so I don't know if it is simply this phone or all phones on this android version.

    Unity does not appear to render, showing the menuScreen widget in the background. On further inspection, Unity is running but it is behind the flutter widgets.

    After clicking Simple Unity demo, unity is invisible but logs show onSceneLoaded events. menuScreen before and after clicking Simple Unity Demo: Screenshot_20210210-175110-small Screenshot_20210210-175119-small

    The orientation test allows me to see the scene for a split second in landscape mode. Screenshot_20210210-175210-small Screenshot_20210210-175135-small

    If I change the Unity player setting to `start in fullscreen mode', the scene also shows up at the bottom. Screenshot_20210210-175700-small

    Deploying the outdated AR samples project with flutter_unity_widget: ^0.1.6+5, does show unity on top. (This phone doesn't have ARcore installed, that is why there is no visible camera image) Screenshot_20210210-184643-small

    To Reproduce Deploy the example project onto an Android device similar to the one listed below. The only changes made to the project:

    • updating minSDKVersion to 25 in build.gradle.
    • Fixing build.cs to allow unity to export, like mentioned here

    The bug is not in version 0.1.6+5 and it is in version 3.0.0 and 3.0.3, I did not test any version in between those yet. I tried the 4.0.0 alpha, but I haven't yet been able to run it without errors, on any phone.

    Desktop

    • OS: Windows 10
    • Unity 2019.4.13f, exported with export android
    • flutter_windows_1.22.6-stable
    • Either flutter_unity_widget: ^3.0.0 and flutter_unity_widget: ^3.0.3 in pubspec.yaml

    Smartphone

    • Device: Wileyfox swift
    • OS: Android 7.1.2, sdk level 25
    • CPU: Qualcomm Snapdragon 410
    • GPU: Adreno 306

    Additional context Both the outdated AR example and the alternative flutter package flutter_unity show Unity normally on this device. That shows that it is capable of running it properly.

    bug help wanted android 
    opened by timbotimbo 29
  • Create new project or use the repo

    Create new project or use the repo

    I follow all the steps for create my project and setup this, but when need add as library the .jar i don't have the same flow, and don't works the question is: Is necessary use the repo for create the unity plugin or should work with a new project create by me. because for example if open in android studio see different the project first variation

    My project, (The icon under Project is a folder and the android folder have [name_android]) image

    The repo (The icon under Project is flutter icon) image

    Add as library:

    This is my project but don't show all the settings. image

    This is the window of the repo when try to add as library image

    Hope that anyone can help me with this please,

    Thanks!

    android ar-foundation 
    opened by Jairolaya12x 26
  • Undefined symbols for architecture arm64:

    Undefined symbols for architecture arm64: "_onUnitySceneLoaded"

    using Flutter 1.22 stable and flutter-unity-view-widget 2.0.0+2.

    I've no idea about the solution for iOS build.

    the error shows below:

     ld: warning: arm64 function not 4-byte aligned: _unwind_tester from /Users/kingtous/projects/cishi-app/ios/UnityLibrary/Libraries/libiPhone-lib.a(unwind_test_arm64.o)
        Undefined symbols for architecture arm64:
          "_onUnitySceneLoaded", referenced from:
              _NativeAPI_onUnitySceneLoaded_m4741E4A6C2A3A84DC595DCA9E6715B0779372985 in Assembly-CSharp.o
             (maybe you meant: _NativeAPI_onUnitySceneLoaded_m4741E4A6C2A3A84DC595DCA9E6715B0779372985)
          "_onUnityMessage", referenced from:
              _NativeAPI_onUnityMessage_mD44345499E1125EA37D67E2892D48D89B448B012 in Assembly-CSharp.o
             (maybe you meant: _NativeAPI_onUnityMessage_mD44345499E1125EA37D67E2892D48D89B448B012)
        ld: symbol(s) not found for architecture arm64
    

    Does this mean there's a problem in my unityLibrary?

    opened by Kingtous 22
  • A problem occurred evaluating project ':flutter_unity_widget'.

    A problem occurred evaluating project ':flutter_unity_widget'.

    Launching lib\main.dart on Android SDK built for x86 in debug mode...
    Initializing gradle...
    Resolving dependencies...
    * Error running Gradle:
    ProcessException: Process "C:\Users\ShuWeiIT-JIangheng\Desktop\flutter_unity_app\android\gradlew.bat" exited abnormally:
    
    FAILURE: Build failed with an exception.
    
    * Where:
    Build file 'C:\SRC\flutter\.pub-cache\hosted\pub.flutter-io.cn\flutter_unity_widget-0.1.3+3\android\build.gradle' line: 37
    
    * What went wrong:
    A problem occurred evaluating project ':flutter_unity_widget'.
    > Project with path ':UnityExport' could not be found in project ':flutter_unity_widget'.
    
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    
    * Get more help at https://help.gradle.org
    
    BUILD FAILED in 0s
      Command: C:\Users\ShuWeiIT-JIangheng\Desktop\flutter_unity_app\android\gradlew.bat app:properties
    
    Finished with error: Please review your Gradle project setup in the android/ folder.
    

    When I finish config project and run it,this problem comes out。I dont know how to handle it

    opened by jiangheng90 22
  • Build iOS, get this:

    Build iOS, get this:

    /Users/desi/development/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_unity_widget-0.1.6+5/ios/Classes/UnityUtils.mm:55:10: error: no visible @interface for 'UnityFramework' declares the selector 'frameworkWarmup:argv:' [ufw frameworkWarmup: g_argc argv: g_argv]; ~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated. note: Using new build systemnote: Planning buildnote: Constructing build description

    ios 
    opened by playstonex 21
  • Trying to run new scenes in demo project crashes

    Trying to run new scenes in demo project crashes

    Describe the bug Hi, I was trying to build scenes from a different unity project in the demo flutter project. Just adding another button to the menu and run this new project. When I build it from Unity everything is fine but when I try to run the flutter project, it crashes when I click on the new button I made for the new scene, or with any button really. I thought trying this would be easier. Is there a guide on how to setup new scenes into new flutter screens. I'm very new to Flutter.

    To Reproduce Steps to reproduce the behavior:

    1. Replaced old unity folder with new project.
    2. Build scene (current scene in the unity build list)
    3. Compile Flutter app
    4. Run app in android and app crashes when level is selected.

    Expected behavior Demo App should run my game when selected.

    Screenshots If applicable, add screenshots to help explain your problem.

    Unity (please complete the following information):

    • OS: Windows 10
    • Version 2022.1.0f1

    Smartphone (please complete the following information):

    • Device: Techno Spark 6 Go
    • OS: Android
    • Version 10

    Additional context Add any other context about the problem here. I used the no_interaction_screen.dart file as a template for the new scence I made. Is there any part where the scene path to Unity should be referenced? I don't know if you need to reference that in the screen file.

    This is the screen file for the New Scene.

    import 'package:flutter/material.dart';
    import 'package:flutter_unity_widget/flutter_unity_widget.dart';
    
    class NewScreen extends StatefulWidget {
      NewScreen({Key key}) : super(key: key);
    
      @override
      _NewScreenState createState() => _NewScreenState();
    }
    
    class _NewScreenState extends State<NewScreen> {
      static final GlobalKey<ScaffoldState> _scaffoldKey =
          GlobalKey<ScaffoldState>();
    
      UnityWidgetController _unityWidgetController;
    
      @override
      void initState() {
        super.initState();
      }
    
      @override
      void dispose() {
        _unityWidgetController.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          key: _scaffoldKey,
          appBar: AppBar(
            title: Text('New Screen'),
          ),
          body: Card(
              margin: const EdgeInsets.all(8),
              clipBehavior: Clip.antiAlias,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.0),
              ),
              child: Stack(
                children: [
                  UnityWidget(
                    onUnityCreated: _onUnityCreated,
                    onUnityMessage: onUnityMessage,
                    onUnitySceneLoaded: onUnitySceneLoaded,
                    webUrl: 'http://localhost:6080/',
                  ),
                ],
              )),
        );
      }
    
      // void setRotationSpeed(String speed) {
      //   _unityWidgetController.postMessage(
      //     'Cube',
      //     'SetRotationSpeed',
      //     speed,
      //   );
      // }
    
      void onUnityMessage(message) {
        print('Received message from unity: ${message.toString()}');
      }
    
      void onUnitySceneLoaded(SceneLoaded scene) {
        print('Received scene loaded from unity: ${scene.name}');
        print('Received scene loaded from unity buildIndex: ${scene.buildIndex}');
      }
    
      // Callback that connects the created controller to the unity controller
      void _onUnityCreated(controller) {
        controller.resume();
        this._unityWidgetController = controller;
      }
    }
    
    opened by rmib200 20
  • Remove Android's white background color.

    Remove Android's white background color.

    Description

    This removes the white background set in Kotlin, which allows us to experiment with a transparent UnityWidget. iOS doesn't need any change as this already works.

    This should not affect most users, because to see any change you need to both manually configure Unity and adjust the android theme.

    See this example of a video widget playing behind Unity to get an idea of the possible results.
    (The video is started on a small delay to show the black flash, which is a flutter bug with AndroidView.)

    https://user-images.githubusercontent.com/11444698/203645680-dcb7812d-e0c6-4373-89f3-79d72bf6bc68.mp4

    See https://github.com/juicycleff/flutter-unity-view-widget/issues/190#issuecomment-1296383215 for more details.

    Type of Change

    • [x] ✨ New feature (non-breaking change which adds functionality)
    • [ ] 🛠️ Bug fix (non-breaking change which fixes an issue)
    • [ ] ❌ Breaking change (fix or feature that would cause existing functionality to change)
    • [ ] 🧹 Code refactor
    • [ ] ✅ Build configuration change
    • [ ] 📝 Documentation
    • [ ] 🗑️ Chore
    opened by timbotimbo 0
  • Lifecycle of Unity Engine

    Lifecycle of Unity Engine

    • When the Unity engine is created and destroyed?
    • How can I destroy it and create it again?

    The scenario is like the following.

    My app uses this widget as a model viewer. When I click an item in a model list, it opens unity widget and shows the model in unity engine. I close it and open another model. I repeat this operation several times and then I get the app crashes (on Android). I think this could be related to memory leak. So I wanted to know the correct usage of lifecycle of this widget

    Thanks in advance

    opened by koreex 4
  • Pods_UnityFramework and Pods_Unity_Phone

    Pods_UnityFramework and Pods_Unity_Phone

    Describe the bug I realized that Pods_UnityFramework and Pods_Unity_Phone appeared under Unity-iPhone/Frameworks, and they appeared red. I think they are just referenced, but they don't exist. This happens when I add firebase SDK to my Unity project. Do I need these two frameworks, or could I delete them?

    To Reproduce Steps to reproduce the behavior:

    1. Add firebase SDK to the Unity project
    2. Export ios build to flutter
    3. open XCode, and then you should see these two frameworks under Unity-iPhone/Frameworks

    Expected behavior Make them not "red," or tell me that I could just delete them without affecting anything.

    Screenshots image

    Unity (please complete the following information):

    • OS: MacOs
    • Version 2021.3.12f1 SILICON LTS

    Smartphone (please complete the following information):

    • Device: iPhone13
    • OS: iOS
    • Version 16.1
    opened by AmazeFPig 1
  • Controller in Web GL doens't work

    Controller in Web GL doens't work

    Describe the bug I am having a problem with the controller, when I am using Web GL. The onCreated method doesn't work, because when I try to send a message to unity, nothing happens.

    To Reproduce Steps to reproduce the behavior:

    1. I do Flutter Export Web GL
    2. I created the method to inicialize the controller
    3. I put a print to see the controller
    4. The message is Instance of 'WebUnityWidgetController', but doesn't work.

    Expected behavior Send a message to unity, for the unity opens the scene.

    Screenshots image

    Unity (please complete the following information):

    • OS: [e.g. iOS] Web
    • Version [e.g. 22] Chrome
    • Unity Version 2022.1.17f1

    Additional context Add any other context about the problem here.

    opened by RamiroNoronha 1
  • Make custom unity package

    Make custom unity package

    Is your feature request related to a problem? Please describe. How about making unity packages instead of distributing via .unitypackage? I don't want to include the FlutterUnityIntegration asset in my version control. I want to include this asset as a dependency in my custom package.

    Describe the solution you'd like Install FlutterUnityIntegration from UPM.

    Describe alternatives you've considered

    Additional context https://docs.unity3d.com/Manual/CustomPackages.html

    opened by siisee11 0
Releases(v4.0.0)
Owner
Rex Raphael
Senior Software Engineer/Architect working with web and cloud technologies. Aspiring tech manager 🤞and I'm not American🤣, I'm asked that alot.
Rex Raphael
An embeddable interpreter for scripting Flutter applications

flutterscript An embeddable interpreter for Flutter applications Getting Started import "package:flutterscript/flutterscript.dart"; main() async {

Isac Canedo 1 Mar 29, 2022
UIWidget is a Unity Package which helps developers to create, debug and deploy efficient, cross-platform Apps.

⚠️ The main repository of UIWidgets has been moved to https://github.com/Unity-Technologies/com.unity.uiwidgets. Please visit the new site if you have

Unity Technologies 1.9k Nov 17, 2022
Flutter list view - An unofficial list view for flutter

Flutter List View I don't like official list view. There are some features don't

null 21 Nov 4, 2022
Grid-View-App - Grid View App For Flutter

grid_view_app practice purpose flutter application Getting Started This project

Md Tarequl Islam 4 Jun 9, 2022
Swipeable button view - Create Ripple Animated Pages With Swipeable Button View

swipeable_button_view You can create ripple animated pages with swipeable_button

cemreonur 3 Apr 22, 2022
-UNDER DEVELOPMENT- a project built demonstrating model view view model architecture

mvvm_project A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Atuoha Anthony 3 Nov 18, 2022
A flutter search engine based on MediaWiki with caching.

Table of contents Project Description Working App Architecture BLoC/Cubit Pattern Caching using HiveDB App UI Project Setup To-Do How to get started w

Shashwat Joshi 42 Nov 7, 2022
Holy Quran Search Engine by Flutter

114 Holy Quran Search App Searching By Word and getting the Surah & the Ayah where the word is located and how many times the word is repeated in qura

Mohaned Yossry 19 Nov 2, 2022
A quickjs engine for flutter.

flutter_qjs English | 中文 This plugin is a simple js engine for flutter using the quickjs project with dart:ffi. Plugin currently supports all the plat

ekibun 117 Nov 9, 2022
Tap Hero Game - An Open Source Flutter Game

Tap Hero ?? ?? TapHero is a casual tapping arcade game. This repo includes Android, iOS, Desktop (macOS, Windows, Linux). For Flutter Web, check the T

Mariano Zorrilla 158 Sep 15, 2022
Video game ui - Video Game App UI In Flutter!

video_game_ui A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Flutter Boy 11 Sep 6, 2022
Color matching game - A Crossplatform Color Matching Game made with Flutter

color_matching_game A Color Matching Game built with Flutter. It is a simple app made without adding a plug-in. Play by specifying the red, green and

Yusuke Ishimi 6 Nov 21, 2022
Rock-Paper-Scissor-Game-Using-Dart - This is a repository of Rock Paper Scissor Game which I developed while learning Dart.

Rock-Paper-Scissor-Game-Using-Dart This is a repository of Rock Paper Scissor Game which I developed while learning Dart. The main.dart file consist o

Nitin Varma 0 Jan 4, 2022
Flutter agenda - Flutter Agenda View Package (pub.dev)

Flutter Agenda View Agenda Widget Package for Flutter Features Image Video Recor

Iliyass Zamouri 3 Apr 15, 2022
A periodic table app with 3D view of the elements built using flutter.

A flutter app which takes you on a 3d visualisation of the 118 elements of the periodic table. promo.mp4 Tech Stack Deployed using How it all began It

Shanwill Pinto 48 Nov 16, 2022
Flutter Split View and Drawer Navigation example

Flutter Split View and Drawer Navigation example This repo contains the source code for this tutorial: Responsive layouts in Flutter: Split View and D

Andrea Bizzotto 32 Nov 17, 2022
Flutter Insert, Update, Delete and add form view dynamic

salesapp Insert, Update, Delete and form view add dynamic. Getting Started This project is a starting point for a Flutter application. A few resources

null 1 Dec 22, 2021
A flutter list view which can drag & move item to change order.

draggable_flutter_list A flutter list view which can drag & move item to change order. some codes come from flutter_list_drag_and_drop fix flutter_lis

刘彦博 40 Sep 22, 2022
Search and view popular Youtube videos with Youtube API in Flutter App

getx_bottom_nav_sample The sample of AnimatedBottomNavBar with GetX 주요 Package 설명 1.url_launcher url_launcher pub.dev flutter 에서 인앱, 외부 브라우저로 연길 시켜 주는

Jacob Ko 1 Dec 25, 2021