Giter VIP home page Giter VIP logo

juicycleff / flutter-unity-view-widget Goto Github PK

View Code? Open in Web Editor NEW
2.1K 53.0 494.0 302.63 MB

Embeddable unity game engine view for Flutter. Advance demo here https://github.com/juicycleff/flutter-unity-arkit-demo

License: BSD 3-Clause "New" or "Revised" License

Ruby 1.68% Swift 7.72% Objective-C 0.72% Dart 33.65% Objective-C++ 0.17% C# 22.53% Kotlin 15.76% JavaScript 0.13% CMake 6.93% C++ 9.88% C 0.83%
unity flutter widget unity3d android-library flutter-plugin flutter-package unityframework game-engine

flutter-unity-view-widget's Introduction

flutter_unity_widget

All Contributors

version MIT License PRs Welcome

Watch on GitHub Star on GitHub

Gitter Discord

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, iOS, Web.

Windows support is a work in progress.

Notes

  • Use Windows or Mac to export and build your project.
    Users on Ubuntu have reported a lot of errors in the Unity export.
  • Emulator support is limited and requires special setup. Please use a physical device for Android and iOS.
  • Supports Unity 2019.4.3 or later, we recommend the latest LTS.
  • Use only OpenGLES3 as Graphics API on Android for AR compatibility.

Notice

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.

Moving forward, versioning of the package will change to match unity releases after proper test. Mind you this does not mean the package is not compatible with other versions, it just mean it's been tested to work with a unity version.

Windows coming soon.

Installation

First depend on the library by adding this to your packages pubspec.yaml:

  • Flutter 3.0.0
dependencies:
  flutter_unity_widget: ^2022.2.0
  • Pre Flutter 3.0.0 (This version will gradually be deprecated)
dependencies:
  flutter_unity_widget: ^2022.1.0+7

Now inside your Dart code you can import it.

import 'package:flutter_unity_widget/flutter_unity_widget.dart';

You will need to open and export a Unity project, even for running the example. Your build will fail if you only include the widget in Flutter!

Preview

30 fps gifs, showcasing communication between Flutter and Unity:

gif gif


Setup

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

  • 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 fuw-XXXX.unitypackage file, found in the unitypackages folder. Try to use the most recent unitypackage available.

Unity project setup

These instructions assume you are using a new Unity project. If you open the example project from this repository, you can move on to the next section Unity Exporting.

  1. Create a folder named unity in your Flutter project folder and move the Unity project into there.
    The Unity export will modify some files in the /android and /ios folders of your flutter project. If your Unity project is in a different location the export might (partially) fail.

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

  1. Make sure you have downloaded a fuw-XXXX.unitypackage file mentioned in prerequisites.

  2. Using Unity (hub), open the Unity project. Go to Assets > Import Package > Custom Package and select the downloaded fuw-XXXX.unitypackage file. Click on Import.

  3. Go to File > Build Settings > Player Settings and change the following under the Other settings > Configuration section:

  • In Scripting Backend, change to IL2CPP

  • (Android) Target Architectures, select ARMv7 and ARM64

  • (Android) For the best compatibility set Active Input Handling to Input Manager (Old) or Both.
    (The new input system has some issues with touch input on Android)

  • (iOS) Select Target SDK depending on where you will run your app (simulator or physical device).
    We recommend starting with a physical device and the Device SDK setting, due to limited simulator support.

  • (Web) Set Publishing settings > Compression format to Brotli or Disabled.
    Some users report that Unity gets stuck on the loading screen with the Gzip setting, due to MIME type errors.

  1. In File > Build Settings, make sure to have at least 1 scene added to your build.

Some options in the Build settings window get overridden by the plugin's export script. Attempting to change settings like Development Build, Script Debugging and Export project in this window will not make a difference. If you end up having to change a build setting that doesn't seem to respond, take a lookat the export script FlutterUnityIntegration\Editor\Build.cs.

Unity exporting

  1. After importing the unitypackage, you should now see a Flutter option at the top of the Unity editor.

  2. Click on Flutter and select the appropriate export option:

  • For android use Export Android Debug or Export Android Release.
    This will export to android/unityLibrary.
  • For iOS use Export iOS Debug or Export iOS Release.
    This 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.

If you use git, you will probably want to add these unityLibrary folders to your gitignore file. These folders can get huge and are not guaranteed to work on another computer.

Proceed to the next section to handle iOS and Android specific setup after the export.

Platform specific setup (after Unity export)

After exporting Unity, you will need to make some small changes in your iOS or Android project.
You will likely need to do this only once. These changes remain on future Unity exports.

ℹ️ Android
  1. Setting the Android NDK
  • If you have Unity and Flutter installed on the same machine, the easiest approach is to use the path of the NDK Unity uses. You can find the path to the NDK in Unity under Edit -> Preferences -> External Tool:

NDK Path

  • Copy the path and paste it into your flutter project at android/local.properties as ndk.dir=.
    (For windows you will need to replace \ with \\.)
    Don't simply copy and paste this, make sure it the path matches your Unity version!
    // mac
    ndk.dir=/Applications/Unity/Hub/Editor/2020.3.19f1/PlaybackEngines/AndroidPlayer/NDK
    // windows
    ndk.dir=C:\\Program Files\\Unity\\Hub\\Editor\\2021.3.13f1\\Editor\\Data\\PlaybackEngines\\AndroidPlayer\\NDK
  • With the above setup, you shouldn't have to define any NDK version or setting in gradle files.
    If you don't have Unity on the device making your Flutter buids, you can instead define it in android/app/build.gradle.
android {

  ndkVersion "21.3.6528147"
}
  • To find the exact version that Unity uses, check source.properties at the NDK path described above.
  1. Depending on your gradle version, you might need to make sure the minSdkVersion set in android\app\build.gradle matches the version that is set in Unity.
    Check the Minimum API Level setting in the Unity player settings, and match that version.

  2. (optional) Fixing Unity plugins.
    The Unity widget will function without this step, but some Unity plugins like ArFoundation will throw mUnityPlayer errors on newer Unity versions.

    This is needed for Unity 2020.3.46+, 2021.3.19 - 2021.3.20 and 2022.2.4 - 2022.3.18.
    This requires a flutter_unity_widget version that is newer than 2022.2.1.

  • 3.1. Open the android/app/build.gradle file and add the following:
     dependencies {
+        implementation project(':flutter_unity_widget')
     }
  • 3.2. Edit your android MainActivity file.
    The default location for Flutter is android/app/src/main/kotlin/<app identifier>/MainActivity.kt.

    If you use the default flutter activity, change it to inherit FlutterUnityActivity:

// MainActivity.kt

+ import com.xraph.plugin.flutter_unity_widget.FlutterUnityActivity;

+ class MainActivity: FlutterUnityActivity() {
- class MainActivity: FlutterActivity() {
  • 3.2. (alternative) If you use a custom or modified Activity, implement the IFlutterUnityActivity interface instead.
// MainActivity.kt

// only do this if your activity does not inherit FlutterActivity

import com.xraph.plugin.flutter_unity_widget.IFlutterUnityActivity;

class MainActivity: CustomActivity(), IFlutterUnityActivity {
    // unity will try to read this mUnityPlayer property
    @JvmField 
    var mUnityPlayer: java.lang.Object? = null;

    // implement this function so the plugin can set mUnityPlayer
    override fun setUnityPlayer(unityPlayer: java.lang.Object?) {
        mUnityPlayer = unityPlayer;
    }
}
  1. The Unity export script automatically sets the rest up for you. You are done with the Android setup.
    But if you want to manually set up the changes made by the export, continue.
Optional manual Android setup
  1. Open the android/settings.gradle file and change the following:
+    include ":unityLibrary"
+    project(":unityLibrary").projectDir = file("./unityLibrary")
  1. Open the android/app/build.gradle file and change the following:
     dependencies {
+        implementation project(':unityLibrary')
     }
  1. open the android/build.gradle file and change the following:
allprojects {
    repositories {
+       flatDir {
+           dirs "${project(':unityLibrary').projectDir}/libs"
+       }
        google()
        mavenCentral()
    }
}
  1. 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.

  1. 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.** {*;}
  1. 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>


ℹ️ iOS
  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.
  1. (Optional) Select the Unity-iPhone/Data folder and change the Target Membership for Data folder to UnityFramework.

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)
         }
     }

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]));
          }
     }
  1. Add the UnityFramework.framework file as a library to the Runner project.
  1. If you use Xcode 14 or newer, and Unity older than 2021.3.17f1 or 2022.2.2f1, your app might crash when running from Xcode.
    Disable the Thread Performance Checker feature in Xcode to fix this.
    - In Xcode go to Product > Scheme > Edit Scheme...
    - Now With Run selected on the left, got to the Diagnostics tab and uncheck the checkbox for Thread Performance Checker.

Setup AR

gif

The following setup for AR is done after making an export from Unity.

Warning: The XR Plugin Management package version 4.3.1 - 4.3.3 has bug that breaks Android exports.

  • The bug accidentally deletes your AndroidManifest.xml file after each build, resulting in a broken export.
    Switch to version 4.2.2 or 4.4 to avoid this.
ℹ️ AR Foundation 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 5 and 6 from the Android Platform specific setup (editing build.gradle and settings.gradle), replacing unityLibrary with arcore_client, unityandroidpermissions and UnityARCore.

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


ℹ️ AR Foundation iOS 7. Open the *ios/Runner/Info.plist* and change the following:
     <dict>
+        <key>NSCameraUsageDescription</key>
+        <string>$(PRODUCT_NAME) uses Cameras</string>
     </dict>

ℹ️ Vuforia Android

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.

Emulators

We recommend using a physical iOS or Android device, as emulator support is limited.
Below are the limited options to use an emulator.

iOS Simulators

The Target SDK option in the Unity player settings is important here.

  • Device SDK exports an ARM build. (Which does NOT work on ARM simulators)
  • Simulator SDK exports and x86 build for simulators.

If you use ARKit or ARFoundation you are out of luck, iOS simulators do NOT support ARKit.

The rest depends on the type of processor in your mac:

(Apple Silicon) Run it on mac directly

  1. Export from Unity using Device SDK as target.
  2. In Xcode, go to the General tab of Runner.
  3. In Supported destinations add Mac (Designed for iPhone) or Mac (Designed for iPad).
  4. Now select this as the target device to run on.
  5. You can now run the app directly on your mac instead of a simulator.

(Intel & Apple Silicon) Use an x86 simulator

  1. Set Simulator SDK in the Unity player settings.

  2. Make sure there are no AR or XR packages included in the Unity package manager.
    (You will get the error symbol not found in flat namespace '_UnityARKitXRPlugin_PluginLoad otherwise)

  3. (Apple Silicon) Get Xcode to use a Rosetta emulator.
    The next step assumes Xcode 14.3 or newer, if you use an older version look up how to start Xcode using Rosetta instead.

  • In Xcode go to Product -> Destination -> Destination Architectures and make sure Rosetta destinations are visible.
  1. Now you need to check the architecture settings in Xcode.
  2. Select Unity-iPhone and go to Build settings -> Architectures.
    If you exported Unity with the Simulator SDK, it should show only x86_64 for architectures.
  3. Now select Runner and change the architecture to exactly match Unity-iPhone.
    Make sure x86_64 is the only entry, not one of multiple.
  4. Now select Pods and click flutter_unity_widget in targets.
    Go to Architectures in build settings again and set Build Active Architecture Only to YES.
    (We want this to only use the active x86_64, not fall back to arm.)
  5. Run Product -> Clean Build Folder to make sure the new architecture settings are used.
  6. Now you should be able to launch Runner on a Simulator using Rosetta.
    On Xcode 14.3 or higher the simulator should have (Rosetta) in the name.
  7. Depending on your Flutter plugins, you might have to change the architecture for other installed Pods as well.

Android emulators

Unity only supports ARM build targets for Android. However most Android emulators are x86 which means they simply won't work.

  • Computer with ARM processor
    If your computer has an ARM processor (e.g. Apple Silicon, Qualcomm) you should be able to emulate Android without issue.
    Create a virtual device using Android studio and make sure that the system image has an ABI that includes 'arm'.

    On macs with Apple Silicon (M1, M2), ARM emulators should be the default install option.

    This was tested on Mac, but not on Linux or Windows.

  • Computer with x86/x64 processor
    If you computer does not have an ARM processor, like most computers running on Intel or AMD, your options are limited.

    You have 2 options:

    • Download an ARM emulator from Android Studio anyway.
      While adding a virtual device in android studio, on the 'System image' screen, select 'other images' and make sure to use and ABI that includes 'arm'.
      The emulator will likely crash immediately or run extremely slow.
      This is not recommended.
    • Use the Chrome OS architecture
      This is not officialy supported by Unity and there is no guarantee that it will work, but the Chrome OS target does seem to work on x86 Android emulators.
      Expect (visual) glitches and bugs
      • Enablex86 (Chrome OS) and x86-64 (Chrome OS) in the Unity player settings before making an export.
        You might now be able to run on an regular Android emulator.
      • Disable these settings again if you want to publish your app.

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<UnityMessageManager>() to get a UnityMessageManager.

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

Examples

Simple Example

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

void main() {
  runApp(
    const MaterialApp(
      home: UnityDemoScreen(),
    ),
  );
}

class UnityDemoScreen extends StatefulWidget {
  const UnityDemoScreen({Key? key}) : super(key: key);

  @override
  State<UnityDemoScreen> createState() => _UnityDemoScreenState();
}

class _UnityDemoScreenState extends State<UnityDemoScreen> {
  static final GlobalKey<ScaffoldState> _scaffoldKey =
      GlobalKey<ScaffoldState>();
  UnityWidgetController? _unityWidgetController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: SafeArea(
        bottom: false,
        child: WillPopScope(
          onWillPop: () async {
            // Pop the category page if Android back button is pressed.
            return true;
          },
          child: Container(
            color: Colors.yellow,
            child: UnityWidget(
              onUnityCreated: onUnityCreated,
            ),
          ),
        ),
      ),
    );
  }

  // Callback that connects the created controller to the unity controller
  void onUnityCreated(controller) {
    _unityWidgetController = controller;
  }
}

Communicating with and from Unity

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

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> 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,
                // <You need a PointerInterceptor here on web>
                child: Card(
                  elevation: 10,
                  child: Column(
                    children: <Widget>[
                      const Padding(
                        padding: 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) {
    _unityWidgetController = controller;
  }

  // Communication from Unity when new scene is loaded to Flutter
  void onUnitySceneLoaded(SceneLoaded? sceneInfo) {
    if (sceneInfo != null) {
      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)

Troubleshooting

Location: Unity

Error:

Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included on the current platform. Only one assembly with the same name is allowed per platform. (Assets/FlutterUnityIntegration/JsonDotNet/Assemblies/AOT/Newtonsoft.Json.dll)

PrecompiledAssemblyException: Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included on the current platform. Only one assembly with the same name is allowed per platform.

Solution: Locate the listed dll file, in this case: Assets/FlutterUnityIntegration/JsonDotNet/Assemblies/AOT/Newtonsoft.Json.dll

  • Option 1: Delete the dll file or rename the file extension (e.g. .dll.txt) to stop it from being imported.
  • Option 2: Uninstall the package that conflicts in the Unity package manager (usually Version control, or Collab). The exact package can be found by looking for newtonsoft in package-lock.json

Location: Unity

Error:

The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'JObject' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'JToken' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'JToken' could not be found (are you missing a using directive or an assembly reference?)

Solution:

Include the Newtonsoft JsonDotNet library. It is likely already included in your project with a wrong file extension: Assets/FlutterUnityIntegration/JsonDotNet/Assemblies/AOT/Newtonsoft.Json.dll.txt Rename the .dll.txt extension to .dll in your file explorer and open Unity again.

Alternatively you can manually add the library from the Unity package manager.


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
     }

Flavors

Recommendation

The easiest way to apply flavors for your app would be: flutter_flavorizr.

If you use flavors in your app you will notice that especially iOS crashes while running or building your app! Here are the necessary steps for flavored apps:

Android

No changes needed. Flavors are applied without any additional setups.

iOS

For your Unity iOS-Build you have to add your flavors to your Unity iOS Configuration.

  1. Check your actual Runner (your app) configurations. If you have for example the flavors:
  • dev
  • prod

Your Runner configurations are looking like this:

iOS Runner Config

So you have the flavors:

  • Debug-dev
  • Profile-dev
  • Release-dev
  • Debug-prod
  • Profile-prod
  • Release-prod

These flavors needs to be added to your Unity-IPhone project.

  1. Go into your Unity-IPhone project -> PROJECT Unity-IPhone -> Info:

Unity-IPhone

Here you can see in the Configurations section only:

  • Release
  • ReleaseForProfiling
  • ReleaseForRunning
  • Debug
  1. Copy Debug configuration twice and rename them to Debug-dev and the second to Debug-prod.

You can do that by selecting + and duplicate the configuration like this:

Duplicate configuration

  1. Repeat this with Release to Release-dev and Release-prod.

  2. Repeat this with Release to Profile-dev and Profile-prod.

  3. Your Unity-IPhone configurations should now look like this:

Unity Configurations

Web

Flutter on default doesn't support --flavor for building web. But you can set your target main.dart entrypoint (with -t main.dart) while running and building. So if you setup your flavors properly there're also no changes needed for web to apply changes for your Flutter-Unity web App.

Known issues

  • Remember to disabled fullscreen in unity player settings to disable unity fullscreen.
  • Unity freezes and crashes on Android, please use OpenGL3 as Graphics API.
  • 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 or iOS

  • Android builds takes forever to complete Unity 2022.1.*, remove these lines from unityLibrary/build.gradle file

    commandLineArgs.add("--enable-debugger") commandLineArgs.add("--profiler-report") commandLineArgs.add("--profiler-output-file=" + workingDir + "/build/il2cpp_"+ abi + "_" + configuration + "/il2cpp_conv.traceevents")

Web GL

Flutter widgets stacked on top of the UnityWidget will not register clicks or taps. This is a Flutter issue and can be solved by using the PointerInterceptor package.

Example usage:

Stack(
  children: [
    UnityWidget(
      onUnityCreated: onUnityCreated,
      onUnityMessage: onUnityMessage,
      onUnitySceneLoaded: onUnitySceneLoaded,
    ),
    Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: PointerInterceptor(
        child: ElevatedButton(
          onPressed: () {
            // do something
          },
          child: const Text('Example button'),
        ),
      ),
    ),

We already integrated this into our Examples in the /example folder.

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!

flutter-unity-view-widget's People

Contributors

ahmadre avatar bssughosh avatar dawiddszewczyk avatar enzo-santos avatar guyluz11 avatar jakeobrien avatar josephcarrington avatar juicycleff avatar keien411 avatar khanhuitse05 avatar mrdavidrees avatar ortes avatar rebarah avatar ricardodalarme avatar royalcoder88 avatar shinriyo avatar timbotimbo avatar timbotimbo2 avatar tizkzks96 avatar tonyhoylerps avatar xcxooxl avatar xoox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flutter-unity-view-widget's Issues

Flutter packages get mapping error

HI i am trying to import the flutter_unity_widgets in to example iOS app, i reinstalled the pods and when i try to add dependency under

cupertino_icons: ^0.1.2
    flutter_unity_widget: ^0.1.6+2


i am getting below error any one know what i am missing here

:```
example arpitas$ flutter packages get
Error detected in pubspec.yaml:
Error on line 11, column 27: Mapping values are not allowed here. Did you miss a colon earlier?

11 │ flutter_unity_widget: ^0.1.6+2
│ ^

Please correct the pubspec.yaml file at /Users/Downloads/flutter-unity-view-widget-master/example/pubspec.yaml

Split up AR and standard examples into separate apps

We'll probably need to split up the AR and standard example into two separate apps, as we can't run both examples without code changes anyway.

The current example might be unclear to the end-user, as they might not understand why the example is not fully functional.

Calling a function from flutter to unity3d

Hi,

Can someone provide an explanation how you can achieve to communicate from flutter to unity3d and back. I have read the documentation and imported the needed files.

At first when I exported it from unity3d to flutter I got this error about NewtonJSON: PrecompiledAssemblyException: Multiple precompiled assemblies with the same name. I then removed the folders Windows and AOT because unity3d found multiple dll's.

After compiling I get the following errror:

Undefined symbols for architecture arm64:
"_onUnityMessage", referenced from:

I try to pause and play unity3d.

Compile errors on Android

The master branch of flutter-unity-view-widget does not compile anymore.

flutter-unity-view-widget/android/src/main/java/com/rexraphael/flutterunitywidget/UnityView.java:50: error: method addUnityViewToBackground in class UnityUtils cannot be applied to given types;
        UnityUtils.addUnityViewToBackground();
                  ^
  required: Activity
  found: no arguments
  reason: actual and formal argument lists differ in length

iPhone Export crashes whole device

Hi,

I was trying to add the flutter_unity_plugin using the normal instructions provided in the Readme.md of this repo. It was throwing out no errors, as I ran the Xcode Build so I ran it on my iPhone SE.
But then, not just the app crashed, but the whole Springboard! The phone showed the shut down animation but after 5 seconds it entered the state it's in when it's just booted. (So no Touch ID sign in, etc.)
When I run it through VSCode or Android Studio the app just crashes after showing the splash screen but the IDE doesn't recognize that it even started. It's just endlessly idling at "Installing and Launching...". It works fine on Android though.
My Configuration :

  • macOS 10.14.6
  • newest versions of the Java JDK (1.8.0_202), Flutter SDK, Dart SDK
  • newest versions of Android Studio (3.5.1), VSCode (1.39.2), Xcode (11.1), Unity (2019.3.0b6)
  • newest versions of the Flutter Plugins (provided screenshot)

Could someone help me with this?

Thanks for any replies!

More informations provided in attachments:

Runner 27.10.19, 16-00.crash.txt
SpringBoard 27.10.19, 16-00.crash.txt

Screenshot 2019-10-27 at 16 08 26
Screenshot 2019-10-27 at 16 09 55

Video Turtorial

Anyone care to make a video tutorial for setting up the example project

iOS Build Successful but Could Not Load on Device

Environment

Xcode: 10.3
Target Platform: iOS - 12.0.1 / iPhone 6S (Device)

Steps to Reproduce

I had the same problem as in #31
After receiving error message:
Undefined symbols for architecture arm64:
"_onUnityMessage", referenced from:

Following the steps in #31 , I removed UnityMessageManager.cs, the JsonDotNet folder and link.xml

The build is successful but there is now a 0_abort_with_payload error

This is what I get in the debug log.
" Referenced from: /var/containers/Bundle/Application/75D04D06-E198-4D91-9B0E-267E82E507BA/Runner.app/Runner Reason: image not found "

Actual Behavior
Screen Shot 2019-09-26 at 2 48 04 pm

Is anybody else having this problem and managed to get around this? Thanks in advance

iOS Flutter Build Build Fail

i have created a build for ios and tried to check initial build but i am getting these errors when i import the UnityMessageManager.cs class in to unity project, anyone here know how to fix this please

Unity version 2019.3.0a4
Xcode Version 11.0 (11A420a)

`
Showing All Errors Only
Ld /Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Unity-iPhone-hhfffylzhgzeisbnroewaaajtaug/Build/Intermediates.noindex/Unity-iPhone.build/ReleaseForRunning-iphoneos/UnityFramework.build/Objects-normal/armv7/Binary/UnityFramework normal armv7 (in target 'UnityFramework' from project 'Unity-iPhone')
cd /Users/arpitasaxena/Downloads/flutter-unity-view-widget-master/ios/UnityExport
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -target armv7-apple-ios9.0 -dynamiclib -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS13.0.sdk -L/Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Unity-iPhone-hhfffylzhgzeisbnroewaaajtaug/Build/Products/ReleaseForRunning-iphoneos -L/Users/arpitasaxena/Downloads/flutter-unity-view-widget-master/ios/UnityExport/Libraries -F/Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Unity-iPhone-hhfffylzhgzeisbnroewaaajtaug/Build/Products/ReleaseForRunning-iphoneos -filelist /Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Unity-iPhone-hhfffylzhgzeisbnroewaaajtaug/Build/Intermediates.noindex/Unity-iPhone.build/ReleaseForRunning-iphoneos/UnityFramework.build/Objects-normal/armv7/UnityFramework.LinkFileList -install_name @rpath/UnityFramework.framework/UnityFramework -Xlinker -rpath -Xlinker @executable_path/Frameworks -Xlinker -rpath -Xlinker @loader_path/Frameworks -Xlinker -map -Xlinker /Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Unity-iPhone-hhfffylzhgzeisbnroewaaajtaug/Build/Intermediates.noindex/Unity-iPhone.build/ReleaseForRunning-iphoneos/UnityFramework.build/UnityFramework-LinkMap-normal-armv7.txt -dead_strip -Xlinker -object_path_lto -Xlinker /Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Unity-iPhone-hhfffylzhgzeisbnroewaaajtaug/Build/Intermediates.noindex/Unity-iPhone.build/ReleaseForRunning-iphoneos/UnityFramework.build/Objects-normal/armv7/UnityFramework_lto.o -fembed-bitcode-marker -stdlib=libc++ -fobjc-arc -fobjc-link-runtime -weak_framework CoreMotion -weak-lSystem -liPhone-lib -framework Security -framework MediaToolbox -framework CoreText -framework AudioToolbox -weak_framework AVFoundation -framework AVKit -framework CFNetwork -framework CoreGraphics -framework CoreMedia -weak_framework CoreMotion -framework CoreVideo -framework Foundation -framework OpenAL -framework OpenGLES -framework QuartzCore -framework SystemConfiguration -framework UIKit -liconv.2 -lil2cpp -Xlinker -dependency_info -Xlinker /Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Unity-iPhone-hhfffylzhgzeisbnroewaaajtaug/Build/Intermediates.noindex/Unity-iPhone.build/ReleaseForRunning-iphoneos/UnityFramework.build/Objects-normal/armv7/UnityFramework_dependency_info.dat -o /Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Unity-iPhone-hhfffylzhgzeisbnroewaaajtaug/Build/Intermediates.noindex/Unity-iPhone.build/ReleaseForRunning-iphoneos/UnityFramework.build/Objects-normal/armv7/Binary/UnityFramework

Undefined symbols for architecture armv7:
"_onUnityMessage", referenced from:
_UnityMessageManager_SendMessageToFlutter_m0ADC2E517A85054AE5BA1D3328255060B20A1570 in Assembly-CSharp.o
_UnityMessageManager_onUnityMessage_mC3031C4585567E720F536DB4EE28B0C20AB8A7C4 in Assembly-CSharp.o
(maybe you meant: _UnityMessageManager_onUnityMessage_mC3031C4585567E720F536DB4EE28B0C20AB8A7C4)
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

`

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 compile fails Undefined symbols for architecture arm64:

Hi
i am trying get a ios build to my iphone, before this i had an error #43 which i fixed by adding - (void)frameworkWarmup:(int)argc argv:(char*[])argv; in UnityFramework.h file but i am getting this now

Xcode's output: ↳ === BUILD TARGET flutter_unity_widget OF PROJECT Pods WITH CONFIGURATION Debug === Undefined symbols for architecture arm64: "_GetAppController", referenced from: -[FUController view] in FlutterUnityWidgetPlugin.o ___20-[FUController view]_block_invoke in FlutterUnityWidgetPlugin.o +[UnityUtils handleAppStateDidChange:] in UnityUtils.o ___27+[UnityUtils createPlayer:]_block_invoke.70 in UnityUtils.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

iOS Build Fails missing Manifest.lock

Hi
I am trying to integrate Unity project in to a native iOS using flutter but before i add my unity project into runner workSpace. i usedpod install to install pods into the project which gave downloaded Pods.xcodeproj and other files to my workspace but when i try to run it i am facing this issue. Inside the POD Folder created by pod install has a manifest.lock file. Any one know how i can clear this issue. thanks in advance

Podfile

`# Uncomment this line to define a global platform for your project

platform :ios, '9.0'

CocoaPods analytics sends network stats synchronously affecting flutter build latency.

ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}

def parse_KV_file(file, separator='=')
file_abs_path = File.expand_path(file)
if !File.exists? file_abs_path
return [];
end
pods_ary = []
skip_line_start_symbols = ["#", "/"]
File.foreach(file_abs_path) { |line|
next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
plugin = line.split(pattern=separator)
if plugin.length == 2
podname = plugin[0].strip()
path = plugin[1].strip()
podpath = File.expand_path("#{path}", file_abs_path)
pods_ary.push({:name => podname, :path => podpath});
else
puts "Invalid plugin specification: #{line}"
end
}
return pods_ary
end

target 'Runner' do
use_frameworks!

Prepare symlinks folder. We use symlinks to avoid having Podfile.lock

referring to absolute paths on developers' machines.

system('rm -rf .symlinks')
system('mkdir -p .symlinks/plugins')

Flutter Pods

generated_xcode_build_settings = parse_KV_file('./Flutter/Generated.xcconfig')
if generated_xcode_build_settings.empty?
puts "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first."
end
generated_xcode_build_settings.map { |p|
if p[:name] == 'FLUTTER_FRAMEWORK_DIR'
symlink = File.join('.symlinks', 'flutter')
File.symlink(File.dirname(p[:path]), symlink)
pod 'Flutter', :path => File.join(symlink, File.basename(p[:path]))
end
}

Plugin Pods

plugin_pods = parse_KV_file('../.flutter-plugins')
plugin_pods.map { |p|
symlink = File.join('.symlinks', 'plugins', p[:name])
File.symlink(p[:path], symlink)
pod p[:name], :path => File.join(symlink, 'ios')
}
end

post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = 'NO'
end
end
end
`

Error

`PhaseScriptExecution [CP]\ Check\ Pods\ Manifest.lock /Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Runner-bfjfmktekmqjiabazqtdhzbvghdr/Build/Intermediates.noindex/Runner.build/Debug-iphoneos/Runner.build/Script-EFAA50626EB4954E5A876416.sh
cd /Users/arpitasaxena/Downloads/flutter-unity-view-widget-master/example/ios
/bin/sh -c /Users/arpitasaxena/Library/Developer/Xcode/DerivedData/Runner-bfjfmktekmqjiabazqtdhzbvghdr/Build/Intermediates.noindex/Runner.build/Debug-iphoneos/Runner.build/Script-EFAA50626EB4954E5A876416.sh

diff: /Users/arpitasaxena/Downloads/flutter-unity-view-widget-master/example/ios/Pods/Manifest.lock: No such file or directory
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
`

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

C# "currentActivity" is null when using inside 'flutter-unity-view-widget'

I have a unity project in flutter and when I want to get the current activity in unity C# using the code below it just return a null value

this is the code
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
and the activity object is null
how should I fix this?
P.S All other third-party libraries in unity that uses this code to get the current activity doesn't work with 'flutter-unity-view-widget'

iOS Support

Hello, is iOS support planned?
I would love to help with testing if necessary, once there's an example available

implementing Vuforia AR

The example file works for me however when I also tried to do that with Vuforia AR which in UnityExport generates a new file 'VuforiaWrapper.aar' that I also dropped into unity-classes.

It gives me an error:

Could not determine the dependencies of task ':flutter_unity_widget:generateDebugRFile'.

Could not resolve all task dependencies for configuration ':flutter_unity_widget:debugRuntimeClasspath'.
Could not find :VuforiaWrapper:.
Required by:
project :flutter_unity_widget > project :UnityExport

Could you please help me to implement it?

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?

java.lang.ClassNotFoundException when sending a message from Unity to Flutter (Android)

I get this error in the debug console (Android Studio) when I send a message in Unity to Flutter.

Error:

E/Unity ( 8367): java.lang.ClassNotFoundException: Didn't find class "com/reactnative/unity/view/UnityUtils" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.rexraphael.flutterunitywidgetexample-A3IZZoUXENEbVBkqDGNLAQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.rexraphael.flutterunitywidgetexample-A3IZZoUXENEbVBkqDGNLAQ==/lib/arm64, /data/app/com.rexraphael.flutterunitywidgetexample-A3IZZoUXENEbVBkqDGNLAQ==/base.apk!/lib/arm64-v8a, /system/lib

image

Code Unity:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Rotate : MonoBehaviour
{
    [SerializeField]
    //Vector3 RotateAmount;
    private float rotSpeed = 5f;

    private UnityMessageManager messanger;
    

    // Start is called before the first frame update
    void Start()
    {
        messanger = new UnityMessageManager();
    }

    private void OnMouseDrag()
    { 
        //Rotate object
        float rotX = Input.GetAxis("Mouse X") * rotSpeed * Mathf.Deg2Rad;
        transform.RotateAround(Vector3.up, -rotX);

        //send message to FLutter
        messanger.SendMessageToFlutter("Test");
    }
}

image

cannot find symbol mUnityPlayer.newIntent(intent);

Hi, i follow your video tutorial but when i build a project, i have this problem:

error

I state with the saying that I have cloned the master project and replaced the unity project with another one, but it did not give any kind of problem when I executed the export.

Issue with installing pods

Hi
i am trying to run pod install i am getting this issue,

Pod File

`# Uncomment this line to define a global platform for your project

platform :ios, '9.0'

CocoaPods analytics sends network stats synchronously affecting flutter build latency.

ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}

def parse_KV_file(file, separator='=')
file_abs_path = File.expand_path(file)
if !File.exists? file_abs_path
return [];
end
pods_ary = []
skip_line_start_symbols = ["#", "/"]
File.foreach(file_abs_path) { |line|
next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
plugin = line.split(pattern=separator)
if plugin.length == 2
podname = plugin[0].strip()
path = plugin[1].strip()
podpath = File.expand_path("#{path}", file_abs_path)
pods_ary.push({:name => podname, :path => podpath});
else
puts "Invalid plugin specification: #{line}"
end
}
return pods_ary
end

target 'Runner' do
use_frameworks!

Prepare symlinks folder. We use symlinks to avoid having Podfile.lock

referring to absolute paths on developers' machines.

system('rm -rf .symlinks')
system('mkdir -p .symlinks/plugins')

Flutter Pods

generated_xcode_build_settings = parse_KV_file('./Flutter/Generated.xcconfig')
if generated_xcode_build_settings.empty?
puts "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first."
end
generated_xcode_build_settings.map { |p|
if p[:name] == 'FLUTTER_FRAMEWORK_DIR'
symlink = File.join('.symlinks', 'flutter')
File.symlink(File.dirname(p[:path]), symlink)
pod 'Flutter', :path => File.join(symlink, File.basename(p[:path]))
end
}

Plugin Pods

plugin_pods = parse_KV_file('../.flutter-plugins')
plugin_pods.map { |p|
symlink = File.join('.symlinks', 'plugins', p[:name])
File.symlink(p[:path], symlink)
pod p[:name], :path => File.join(symlink, 'ios')
}
end

post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = 'NO'
end
end
end
`

ERROR

[!] CocoaPods could not find compatible versions for pod "flutter_string_encryption": In Podfile: flutter_string_encryption (from .symlinks/plugins/flutter_string_encryption/ios`)

Specs satisfying the flutter_string_encryption (from .symlinks/plugins/flutter_string_encryption/ios) dependency were found, but they required a higher minimum deployment target.`

Could not find method implementation() for arguments [project ':UnityExport']

Hello,

I followed the video (and also double checked everything with the docs), however when I try to build my android project, I am getting this error (sorry if this is not the right place to post this, I am a beginner in both flutter and unity):

Finished with error: Please review your Gradle project setup in the android/ folder.

  • Error running Gradle:
    ProcessException: Process "/Users/ceciliamzayek/celuna_test/android/gradlew" exited abnormally:

FAILURE: Build failed with an exception.

  • Where:
    Build file '/Users/ceciliamzayek/celuna_test/android/build.gradle' line: 20

  • What went wrong:
    A problem occurred evaluating root project 'android'.

Could not find method implementation() for arguments [project ':UnityExport'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

  • 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: /Users/ceciliamzayek/celuna_test/android/gradlew app:properties

v0.1.6+5 breaks Xcode compile

Due to the recent changes in the FlutterUnityWidgetPlugin.m file, the line [GetAppController() setUnityMessageHandler: ^(const char* message) is breaking the compiling. I needed to fix it by manually download v0.1.6+4 again from the flutter page, because whatever version number I add in the pubspec.yaml file, it forces the v0.1.6+5 version.
I would appreciate if someone could look into what the problem is, as I have not much experience in Objective C and Swift.
Thanks!

Button doesn't detect tapping

Expected: I've a unity project with a button and a background, when the button is clicked the background image should change.

What's happening in flutter project: the button is not clickable at all, it doesn't detect the click even it's working fine on unity.

any solutions?

Example for onUnityMessage()

Is it possible to get an example in pseudo code on how to use the onUnityMessage with Flutter and Unity? I would like to let Flutter know, when an user clicked 'Exit' in the Unity game.

postMessage method not working

I'm trying to use postMessage to call a method on Unity and I'm getting the following error:

/MethodChannel#unity_view_0( 6284): Failed to handle method call
E/MethodChannel#unity_view_0( 6284): java.lang.ClassCastException
E/MethodChannel#unity_view_0( 6284): 	at io.flutter.plugin.common.MethodCall.argument(MethodCall.java:74)
E/MethodChannel#unity_view_0( 6284): 	at com.rexraphael.flutterunitywidget.FlutterUnityView.onMethodCall(FlutterUnityView.java:54)
E/MethodChannel#unity_view_0( 6284): 	at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:201)
E/MethodChannel#unity_view_0( 6284): 	at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:88)
E/MethodChannel#unity_view_0( 6284): 	at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:219)
E/MethodChannel#unity_view_0( 6284): 	at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#unity_view_0( 6284): 	at android.os.MessageQueue.next(MessageQueue.java:325)
E/MethodChannel#unity_view_0( 6284): 	at android.os.Looper.loop(Looper.java:142)
E/MethodChannel#unity_view_0( 6284): 	at android.app.ActivityThread.main(ActivityThread.java:6494)
E/MethodChannel#unity_view_0( 6284): 	at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#unity_view_0( 6284): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
E/MethodChannel#unity_view_0( 6284): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
E/flutter ( 6284): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, null, null)
E/flutter ( 6284): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:564:7)
E/flutter ( 6284): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:302:33)
E/flutter ( 6284): <asynchronous suspension>
E/flutter ( 6284): #2      UnityWidgetController.postMessage (package:flutter_unity_widget/flutter_unity_widget.dart:44:14)
E/flutter ( 6284): #3      _UnityTestScreenState.build.<anonymous closure> (package:hydrocephaly_app/unity_test.dart:43:48)
E/flutter ( 6284): #4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14)
E/flutter ( 6284): #5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30)
E/flutter ( 6284): #6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24)
E/flutter ( 6284): #7      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9)
E/flutter ( 6284): #8      TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:177:9)
E/flutter ( 6284): #9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:436:9)
E/flutter ( 6284): #10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
E/flutter ( 6284): #11     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
E/flutter ( 6284): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:221:19)
E/flutter ( 6284): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22)
E/flutter ( 6284): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter ( 6284): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter ( 6284): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter ( 6284): #17     _rootRunUnary (dart:async/zone.dart:1136:13)
E/flutter ( 6284): #18     _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 6284): #19     _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter ( 6284): #20     _invoke1 (dart:ui/hooks.dart:233:10)
E/flutter ( 6284): #21     _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5)
E/flutter ( 6284): 

This is how I'm calling it on flutter:

_unityWidgetController.postMessage("Cube", "ChangeObjMaterial", "_");

Add another .jar file to project

I have made Unity Project it uses some other jar file itself and It is working in mobile by "Build and Run" in Unity Editor.
Now I am integrating the same project in Flutter so I have exported project to flutter and I have 2 jar files in the exported lib folder (like the image below)
you have created some special folder for flutter-unity-view-widget jar files(unity-classes.jar) and imported it as a project in sample project.
how can I add another jar file to my flutter project?
img

IOS flutter_unity_widget build failed (UnityAppController)

I'm having the following errors while building the IOS after following the documentation steps.
Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_UnityAppController", referenced from: objc-class-ref in FlutterUnityWidgetPlugin.o objc-class-ref in UnityUtils.o ld: symbol(s) not found for architecture x86_64
Another project:
Undefined symbols for architecture x86_64: "_GetAppController", referenced from: -[FUController view] in FlutterUnityWidgetPlugin.o ___20-[FUController view]_block_invoke in FlutterUnityWidgetPlugin.o +[UnityUtils handleAppStateDidChange:] in UnityUtils.o ___27+[UnityUtils createPlayer:]_block_invoke.68 in UnityUtils.o ld: symbol(s) not found for architecture x86_64
any clues?

Clicking inputfield in Unity does not open keyboard (and enable the inputfield?)

With my Unity game I have a scene where a user can fill in an username and email address. These two last items are inputfields, but I'm having issues with this.

When I click on the inputfields nothing happens. I don't see a cursor in the inputfield and the keyboard doesn't pop up.

When I build it native for android it works.

Any tips or is this a bug? I can't find a solution in Unity especially when the native android build works perfect. I do have a 6 buttons in this scene and those work.. in the sense that I can click them and they activate.

AR Foundation for ios

is supporting ios for AR Foundation under consideration? I want to create an Ar App using flutter and unity that will be released within 6 months. will AR Foundation for IOS be supported untill then?

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!

Contributors Needed

If you love to improve this library, please let's have a discussion here and see how to improve it. I am a little busy with some projects atm, but hope to be fully back on this soonest, and also releasing a very good example using the library. @thomas-stockx we can talk here :)

Documentation unclear java module

Hello,

I do not understand a step in the readme, what is this supposed to mean ?

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 /android/UnityExport/lib folder

I do not understand what i am supposed to do here.

Thanks in advance.

Failed to initialize Vuforia Engine

I have made Unity Project with Vuforia and It is working in mobile by "Build and Run" in Unity Editor.

Now I am integrating same project in Flutter so I have exported project to flutter.

I am facing below issue:
I/Unity ( 3247): Vuforia.PlatformRuntimeInitialization:InitPlatform() I/Unity ( 3247): I/Unity ( 3247): (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35) I/Unity ( 3247): E/Unity ( 3247): **NullReferenceException: Object reference not set to an instance of an object.** E/Unity ( 3247): at **Vuforia.AndroidDatasets.AddExternalDatasetSearchDirs** () [0x00000] in <00000000000000000000000000000000>:0 E/Unity ( 3247): at Vuforia.PlatformRuntimeInitialization.InitPlatform () [0x00000] in <00000000000000000000000000000000>:0 E/Unity ( 3247): E/Unity ( 3247): (Filename: currently not available on il2cpp Line: -1) E/Unity ( 3247): I/Unity ( 3247): Initializing Vuforia Engine I/Unity ( 3247): UnityEngine.Logger:Log(LogType, Object) I/Unity ( 3247): Vuforia.VuforiaRuntime:InitVuforia()

Screenshot_20190830-085853

Unity Export Folder : https://drive.google.com/open?id=1zipwU1nZchGI4BpytKbOU4juwtIHz3zH

Let me know if any more information is required.

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

Unable to find a matching variant of project :UnityExport:

Hi there,

Using your example project as a code base, I got the exported unity android project as explained here and copied the output to UnityExport folder. When tried to build gradle I'm getting the following results:


* What went wrong:
Could not determine the dependencies of task ':app:preDebugBuild'.
> Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
   > Could not resolve project :UnityExport.
     Required by:
         project :app > project :flutter_unity_widget
      > Unable to find a matching variant of project :UnityExport:
          - Variant 'debugApiElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
              - Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
              - Required org.gradle.usage 'java-runtime' and found incompatible value 'java-api'.
          - Variant 'debugBundleElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'debug' but no value provided.
              - Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but no value provided.
              - Required org.gradle.usage 'java-runtime' and found incompatible value 'android-bundle'.
          - Variant 'debugMetadataElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
              - Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Metadata'.
              - Required org.gradle.usage 'java-runtime' but no value provided.
          - Variant 'debugRuntimeElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
              - Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
              - Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
          - Variant 'releaseApiElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
              - Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
              - Required org.gradle.usage 'java-runtime' and found incompatible value 'java-api'.
          - Variant 'releaseBundleElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'debug' but no value provided.
              - Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but no value provided.
              - Required org.gradle.usage 'java-runtime' and found incompatible value 'android-bundle'.
          - Variant 'releaseMetadataElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
              - Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Metadata'.
              - Required org.gradle.usage 'java-runtime' but no value provided.
          - Variant 'releaseRuntimeElements':
              - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
              - Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
              - Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.

Flutter doctor output.

C:\temp\flutter-unity-view-widget-master\example>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.7.8+hotfix.4, on Microsoft Windows [Version 10.0.18362.295], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.4)
[√] VS Code (version 1.38.0)
[√] Connected device (2 available)

• No issues found!

Any idea what could be the problem?

Thanks.

iOS deploy not working

This is the error I get after following all steps out of the documentation. Using Unity3D v.2019.3.0a11 and the latest version of flutter-unity-view-widget and the latest version of Flutter:

2019-08-11 00:35:01.400320+0200 Runner[1571:278941] Built from 'trunk' branch, Version '2019.3.0a11 (6fa9444d8a5d)', Build type 'Release', Scripting Backend 'il2cpp'
no boot config - using default values

Could you provide a fix or help.

Thank you.

Unable to find a matching variant of project :UnityExport: , Working in debug but not as release

The project is working fine with "flutter run" in debug mode.

But getting an error when trying to run "flutter run --release" or generating the apk "flutter build apk --release"

running as release results the following exception or build apk:
`FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':app:lintVitalRelease'.

Could not resolve all artifacts for configuration ':flutter_unity_widget:profileRuntimeClasspath'.
Could not resolve project :UnityExport.
Required by:
project :flutter_unity_widget
> Unable to find a matching variant of project :UnityExport:
- Variant 'debugApiElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'profile' and found incompatible value 'debug'.
- Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Required org.gradle.usage 'java-runtime' and found incompatible value 'java-api'.
- Variant 'debugRuntimeElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'profile' and found incompatible value 'debug'.
- Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
- Variant 'releaseApiElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'profile' and found incompatible value 'release'.
- Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Required org.gradle.usage 'java-runtime' and found incompatible value 'java-api'.
- Variant 'releaseRuntimeElements':
- Required com.android.build.api.attributes.BuildTypeAttr 'profile' and found incompatible value 'release'.
- Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
- Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
- Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
`

Unable to build examples

flutter-unity-view-widget/example$ flutter build apk
Initializing gradle...                                              0.6s
Resolving dependencies...                                               
* Error running Gradle:
ProcessException: Process "/home/shrkamat/AndroidStudioProjects/skm/flutter-unity-view-widget/example/android/gradlew" exited abnormally:

FAILURE: Build failed with an exception.

* Where:
Build file '/home/shrkamat/AndroidStudioProjects/skm/flutter-unity-view-widget/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: /home/shrkamat/AndroidStudioProjects/skm/flutter-unity-view-widget/example/android/gradlew app:properties


Please review your Gradle project setup in the android/ folder.

build failed in android

unity version is 2019..3.0b1

I have export for android, then make unity-classes.jar as library.
and copy unity-classes folder from example, delete unity-classes/unity-classes.jar like tutorial video, then move UnityExport/libs/unity-classes.jar to unity-classes folder

when I run flutter build apk it will tell me can't find UnityExport.

so, I add

include ":UnityExport"
project(":UnityExport").projectDir = file("./UnityExport")

to ./android/setting.gradle, and it tell me that can't found unity-class

so i add

include ':app', ':unity-classes'

in it, then run build command, it tell me that:

FAILURE: Build failed with an exception.                                
                                                                        
* What went wrong:                                                      
Execution failed for task ':app:lintVitalRelease'.                      
> Could not resolve all artifacts for configuration ':flutter_unity_widget:profileRuntimeClasspath'.
   > Could not resolve project :UnityExport.                            
     Required by:                                                       
         project :flutter_unity_widget                                  
      > Unable to find a matching variant of project :UnityExport:      
          - Variant 'debugApiElements':                                 
              - Required com.android.build.api.attributes.BuildTypeAttr 'profile' and found incompatible value 'debug'.
              - Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
              - Required org.gradle.usage 'java-runtime' and found incompatible value 'java-api'.
          - Variant 'debugRuntimeElements':                             
              - Required com.android.build.api.attributes.BuildTypeAttr 'profile' and found incompatible value 'debug'.
              - Found com.android.build.api.attributes.VariantAttr 'debug' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
              - Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
          - Variant 'releaseApiElements':                               
              - Required com.android.build.api.attributes.BuildTypeAttr 'profile' and found incompatible value 'release'.
              - Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
              - Required org.gradle.usage 'java-runtime' and found incompatible value 'java-api'.
          - Variant 'releaseRuntimeElements':                           
              - Required com.android.build.api.attributes.BuildTypeAttr 'profile' and found incompatible value 'release'.
              - Found com.android.build.api.attributes.VariantAttr 'release' but wasn't required.
              - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found compatible value 'Aar'.
              - Required org.gradle.usage 'java-runtime' and found compatible value 'java-runtime'.
                                                                        
* 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 6s                                         

what should i do?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.