Git Product home page Git Product logo

flutter-unity's Introduction

flutter_unity

A Flutter plugin for embedding Unity projects in Flutter projects.

Both Android and iOS are supported.

Usage

To use this plugin, add flutter_unity as a dependency in your pubspec.yaml file.

Example

Refer to the example project and the included Unity project.

Testing

To test this plugin, do the following:

  1. Run git clone https://github.com/Glartek/flutter-unity.git to create a local copy of flutter-unity.
  2. Open flutter-unity in Android Studio.

Android

  1. Connect your Android device and run the project.

iOS

  1. Configure the example project and the included Unity project.
  2. Connect your iOS device and run the project.

Configuring your Unity project

Android

  1. Go to File > Build Settings... to open the Build Settings window.
  2. Select Android and click Switch Platform.
  3. Click Add Open Scenes.
  4. Check Export Project.
  5. Click Player Settings... to open the Player Settings window.
  6. In the Player Settings window, configure the following:
Setting Value
Resolution and Presentation > Start in fullscreen mode No
Other Settings > Rendering > Graphics APIs OpenGLES3
Other Settings > Configuration > Scripting Backend IL2CPP
Other Settings > Configuration > Target Architectures ARMv7, ARM64
  1. Close the Player Settings window.
  2. Click Export and save as unityExport.

iOS

  1. Go to File > Build Settings... to open the Build Settings window.
  2. Select iOS and click Switch Platform.
  3. Click Add Open Scenes.
  4. Click Build and save as UnityProject.

Configuring your Flutter project

Android

  1. Copy the unityExport folder to <your_flutter_project>/android/unityExport.
  2. Run flutter pub run flutter_unity:unity_export_transmogrify.
  3. Open <your_flutter_project>/android/unityExport/build.gradle and check if buildTypes { profile {} } is present. If not, add the following:
buildTypes {
    profile {}
}

Refer to the example project's unityExport/build.gradle.

  1. Open <your_flutter_project>/android/build.gradle and, under allprojects { repositories {} }, add the following:
flatDir {
    dirs "${project(':unityExport').projectDir}/libs"
}

Refer to the example project's build.gradle.

  1. Open <your_flutter_project>/android/settings.gradle and add the following:
include ':unityExport'

Refer to the example project's settings.gradle.

  1. Open <your_flutter_project>/android/app/src/main/AndroidManifest.xml and add the following:
<uses-permission android:name="android.permission.WAKE_LOCK"/>

Refer to the example project's AndroidManifest.xml.

Steps 1, 2 and 3 must be repeated for every new build of the Unity project.

iOS

  1. Copy the UnityProject folder to <your_flutter_project>/ios/UnityProject and open <your_flutter_project>/ios/Runner.xcworkspace in Xcode.
  2. Go to File > Add Files to "Runner"..., and add <your_flutter_project>/ios/UnityProject/Unity-iPhone.xcodeproj.
  3. Select Unity-iPhone/Data, and, in the Inspectors pane, set the Target Membership to UnityFramework.
  4. Select Unity-iPhone, select PROJECT : Unity-iPhone, and, in the Build Settings tab, configure the following:
Setting Value
Build Options > Enable Bitcode No
Linking > Other Linker Flags -Wl,-U,_FlutterUnityPluginOnMessage
  1. Select Runner, select TARGETS : Runner, and, in the General tab, configure the following:
Setting Value
Frameworks, Libraries, and Embedded Content
Name Embed
UnityFramework.framework Embed & Sign
  1. Select Runner/Runner/Info.plist, and configure the following:
Key Type Value
io.flutter.embedded_views_preview Boolean YES

Steps 1, 3 and 4 must be repeated for every new build of the Unity project.

Exchanging messages between Flutter and Unity

Flutter

To send a message, define the onCreated callback in your UnityView widget, and use the send method from the received controller.

To receive a message, define the onMessage callback in your UnityView widget.

Unity

To send and receive messages, include FlutterUnityPlugin.cs in your project, and use the Messages.Send and Messages.Receive methods.

A Message object has the following members:

  • id (int)

A non-negative number representing the source view when receiving a message, and the destination view when sending a message. When sending a message, it can also be set to a negative number, indicating that the message is intended for any existing view.

  • data (string)

The actual message.

Refer to the included Unity project's Rotate.cs.

flutter-unity's People

Contributors

cookiejarlid avatar ericloureiro avatar joaopedro735 avatar marcotuna avatar ritheshsalyan 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

flutter-unity's Issues

onMessage never triggered

only log: class com.glartek.flutter_unity.FlutterUnityPlugin(30754): onMessage: {"id":1,"data":"OK"}
UnityViewMessageCallback not called.
please help me!

error running android studio

just download the git project and try to run in android studio ...

Launching lib/main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
✓ Built build/app/outputs/flutter-apk/app-debug.apk.
E/AndroidRuntime(10313): FATAL EXCEPTION: main
E/AndroidRuntime(10313): Process: com.glartek.flutter_unity_example, PID: 10313
E/AndroidRuntime(10313): java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.glartek.flutter_unity_example-Se7uMUHVBHW2RTh1TZlpyw==/base.apk"],nativeLibraryDirectories=[/data/app/com.glartek.flutter_unity_example-Se7uMUHVBHW2RTh1TZlpyw==/lib/x86, /data/app/com.glartek.flutter_unity_example-Se7uMUHVBHW2RTh1TZlpyw==/base.apk!/lib/x86, /system/lib, /system/product/lib]]] couldn't find "libmain.so"
E/AndroidRuntime(10313): at java.lang.Runtime.loadLibrary0(Runtime.java:1067)
E/AndroidRuntime(10313): at java.lang.Runtime.loadLibrary0(Runtime.java:1007)
E/AndroidRuntime(10313): at java.lang.System.loadLibrary(System.java:1667)
E/AndroidRuntime(10313): at com.unity3d.player.UnityPlayer.(Unknown Source:13)
E/AndroidRuntime(10313): at com.glartek.flutter_unity.FlutterUnityPlugin.onActivity(FlutterUnityPlugin.java:98)
E/AndroidRuntime(10313): at com.glartek.flutter_unity.FlutterUnityPlugin.onAttachedToActivity(FlutterUnityPlugin.java:61)
E/AndroidRuntime(10313): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.add(FlutterEnginePluginRegistry.java:143)
E/AndroidRuntime(10313): at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:16)
E/AndroidRuntime(10313): at com.glartek.flutter_unity_example.MainActivity.configureFlutterEngine(MainActivity.java:11)
E/AndroidRuntime(10313): at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onAttach(FlutterActivityAndFragmentDelegate.java:181)
E/AndroidRuntime(10313): at io.flutter.embedding.android.FlutterActivity.onCreate(FlutterActivity.java:410)
E/AndroidRuntime(10313): at android.app.Activity.performCreate(Activity.java:7802)
E/AndroidRuntime(10313): at android.app.Activity.performCreate(Activity.java:7791)
E/AndroidRuntime(10313): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
E/AndroidRuntime(10313): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
E/AndroidRuntime(10313): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
E/AndroidRuntime(10313): at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
E/AndroidRuntime(10313): at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
E/AndroidRuntime(10313): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime(10313): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
E/AndroidRuntime(10313): at android.os.Handler.dispatchMessage(Handler.java:107)
E/AndroidRuntime(10313): at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime(10313): at android.app.ActivityThread.main(ActivityThread.java:7356)
E/AndroidRuntime(10313): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(10313): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/AndroidRuntime(10313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Waiting for Android SDK built for x86 to report its views...
Debug service listening on ws://127.0.0.1:45195/30uIPUfFSxs=/ws
Syncing files to device Android SDK built for x86...

Android Touch is not working

Describe the bug
I am trying since weeks to fix the android version to be able to react to TouchEvents, but I don't know why Touch is not working for Android. We implemented the New Input System and it's working very good for iOS. No problems there. But on Android nothing is happening and no error messages, just this:

Bildschirmfoto 2021-12-15 um 20 57 09

To Reproduce
Steps to reproduce the behavior:

  1. Import the new Input System into your Project
  2. Import one of the samples from Unity itself
  3. Try to run your app on Android
  4. Try out the Touch

Expected behavior
Android Touch is working.

Smartphone (please complete the following information):

  • Device: Pixel 4 - Android
  • OS: 11

Unity

  • Version: 2020.3.19f1
  • Input-System Version: 1.2.0

Additional context
I did a lot of Research, asked in Groups, Discord, Googled, looked up the Warnings....nothing!

Does this work with AR Foundation?

Well-done with this package and really appreciate it! The example worked flawlessly. Just wondering if this works with AR? I tried including AR Foundation (ARkit) to the project, and tried to run it to a physical device (iphone). And got the following error.

2020-08-22 06:06:36.264217+0700 Runner[495:36813] Metal API Validation Enabled
2020-08-22 06:06:36.405163+0700 Runner[495:37060] flutter: Observatory listening on http://127.0.0.1:53927/_IwMpeW9Chc=/
2020-08-22 06:06:38.018470+0700 Runner[495:36813] Built from '2019.3/staging' branch, Version '2019.3.5f1 (d691e07d38ef)', Build type 'Release', Scripting Backend 'il2cpp'
-> applicationDidFinishLaunching()

Setting UIViewControllerBasedStatusBarAppearance to NO is no longer supported.
Apple actively discourages that, and all application-wide methods of changing status bar appearance are deprecated

-> applicationWillEnterForeground()
-> applicationDidBecomeActive()
-> applicationWillEnterForeground()
-> applicationDidBecomeActive()
[Subsystems] Discovering subsystems at path /var/containers/Bundle/Application/A5A6CB63-972B-450C-A3B0-D57CAB240E5B/Runner.app/Frameworks/UnityFramework.framework/Data/UnitySubsystems
[Subsystems] No descriptors matched for examples in UnitySubsystems/UnityARKit/UnitySubsystemsManifest.json.
[Subsystems] 1 'inputs' descriptors matched in UnitySubsystems/UnityARKit/UnitySubsystemsManifest.json
[Subsystems] No descriptors matched for displays in UnitySubsystems/UnityARKit/UnitySubsystemsManifest.json.
[Subsystems] 1 'meshings' descriptors matched in UnitySubsystems/UnityARKit/UnitySubsystemsManifest.json
GfxDevice: creating device client; threaded=1
2020-08-22 06:06:38.094059+0700 Runner[495:37049] flutter: onUnityViewCreated
Initializing Metal device caps: Apple A11 GPU
(lldb)

App crashes sometimes while starting the unity player

Sometime (very rarely though) the app crashes on launching the unity player. No log trace available for any error.

But on starting the player, there is this log.

PlatformViewsController(19429): Creating a virtual display of size: [720, 1457] may result in
problems(https://github.com/flutter/flutter/issues/2897).It is larger than the device screen size: [720, 1425].

Smartphone (please complete the following information):

  • Device: Android
  • OS: Android 10.0

Black Screen of window of unity in flutter

Hello everyone,
after embed unity in flutter, window of unity in flutter is black, the point is it shows splash screen of unity but after that I got Black Screen. I think its some issue about exporting in unity. whenever I build APK inside unity, it works but when I embed it in flutter, I mean do steps of exporting project for use in flutter, I got Black Screen. I use Unity 2019.3.13f1. what is problem? in which version of unity, flutter tested?

Thanks

Problem setting up for iOS

I tried the sample project and it runs fine in Android. Many thanks for your work. Much appreciated.

However, I have difficulties to get it up and running on iOS. I followed the instructions for setting it up with xcode but I simply cannot get it to work. I am still on Mojave and xcode Version 11.3.1 (I cannot upgrade for various reasons).
Also, my experience with xcode and ios development is nearly null and this is the reason I went with Flutter in the first place.

Any chance someone could write down more detailed instructions for iOS (step-by-step) to get the example running? A video on YouTube might be even better.
I think this would benefit also others when using your plugin.

Thanks.

Unclear how to set an ID for a UnityView

In the docs it states:

A Message object has the following members:

id (int)

A non-negative number representing the source view when receiving a message, and the destination view when sending a message. When sending a message, it can also be set to a negative number, indicating that the message is intended for any existing view.

However it's unclear how to control what ID a source view has when creating one in Flutter. For example, I would have expected to be able to pass an ID when creating a UnityView:

 @override
  Widget build(BuildContext context) {
    return UnityView(
      id: myUnityViewId,   // <=== There doesn't seem to be an ID property, so how do I set one?
      onCreated: onUnityViewCreated,
      onReattached: onUnityViewReattached,
      onMessage: onUnityViewMessage,
    );
  }

Am I missing something?

UnityFramework does not contain bitcode.

I tried setting up the example project and follow all steps, but Xcode throws an error when building:

'/Users/Marsel/Library/Developer/Xcode/DerivedData/Runner-auggbmmkjsruwmaqfgadcbpzugzp/Build/Products/Debug-iphoneos/UnityFramework.framework/UnityFramework' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. file '/Users/Marsel/Library/Developer/Xcode/DerivedData/Runner-auggbmmkjsruwmaqfgadcbpzugzp/Build/Products/Debug-iphoneos/UnityFramework.framework/UnityFramework' for architecture arm64

Screen Shot 2021-03-11 at 2 52 30 PM

Screen Shot 2021-03-11 at 2 52 17 PM

I've already set in Build Setting Enable Bitcode to NO and added the requiere linker flags.

I tried flutter clean, pod deintegrate, deleting Derived Data folder but still getting the same error.

Both Unity 2019.4.2f1 and 2020.2.6f1.
Xcode 12.4

Linker issue on iOS

After following the configuration steps and trying to build for iOS, I get the following linker message.

Undefined symbols for architecture arm64:
      "_FlutterUnityPluginOnMessage", referenced from:
          _Messages_FlutterUnityPluginOnMessage_mA8EF48D78A17E613D890457ACF4A0DF
          21A4E0853 in Assembly-CSharp.o
         (maybe you meant:
         _Messages_FlutterUnityPluginOnMessage_mA8EF48D78A17E613D890457ACF4A0DF2
         1A4E0853)
    ld: symbol(s) not found for architecture arm64

Steps to reproduce the behavior:

  1. Setup a new project or use the example from the repo
  2. Configure project for iOS
  3. Build using either xcode or flutter run
  4. Observe error in build output.

Expected behavior
I would expect the project to build and deploy to my device.

Smartphone (please complete the following information):

  • Device: iPhone
  • OS: iOS 14

clang: error: no such file or directory: '_FlutterUnityPluginOnMessage'

Describe the bug
I can't build for iOS. I follow the instructions, but I always get the same error - clang: error: no such file or directory: '_FlutterUnityPluginOnMessage'
Command Ld failed with a nonzero exit code <---- logs from xCode

another log from Idea

Failed to build iOS app
Error output from Xcode build:

** BUILD FAILED **

Xcode's output:

/Users//IdeaProjects/flutter-unity-/ios/Classes/FlutterUnityPlugin.m:3:9: fatal error: 'UnityFramework / UnityFramework.h' file not found
#import <UnityFramework / UnityFramework.h>
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
note: Using new build system
note: Building targets in parallel
note: Planning build
note: Constructing build description

To Reproduce
Steps to reproduce the behavior:

  1. follow the instructions for ios build

Smartphone (please complete the following information):

  • iPhone 11
  • Flutter 1.17.5
  • xCode 11.6 (11E708)
  • Unity 2019.3.7f1

P.S. sorry for my english

Unity player changes the screen orientation of Flutter App permanently

Describe the bug
When navigating from Screen A (Portrait) to Screen B (Unity Player with Landscape Orientation), the screen orientation is permanently set to landscape. Navigating back to Screen A from Screen B also keeps the app in Landscape mode (which was enforced by Screen.orientation API in Unity)

Expected behavior
Navigating back to Screen A from Screen B should bring the App orientation to default.

Smartphone (please complete the following information):

  • Device: Android
  • OS: Android 10

accomodating unity's new input system package

the flutter-unity plugin doesnt work with unity's new input system package

i understand that there are some others who issued bug reports and their solution was to downgrade to the old input manager, but i cant do that due to client's unity project files depending on the new input system

Im hoping theres a workaround for the plugin or for the plugin to be updated to be able to use unity's new input system package

Fails to build and run for iOS

Describe the bug

Fails to build and run for iOS with following output:

Launching lib/main.dart on iPhone in debug mode...
Automatically signing iOS for device deployment using specified development team in Xcode project: ZP4N569NB5
Xcode build done.                                            5.4s
Failed to build iOS app
Error output from Xcode build:
↳
    2020-08-12 17:18:24.534 xcodebuild[34553:236382]  DTDeviceKit: deviceType from 38ad642af5b1c27878b59e12ad50adb0ce78c4f4 was NULL
    ** BUILD FAILED **
Xcode's output:
↳
    /Users/tmw/.pub-cache/hosted/pub.dartlang.org/flutter_unity-0.2.1+4/ios/Classes/FlutterUnityPlugin.m:3:9: fatal error: 'UnityFramework/UnityFramework.h' file not found
    #import <UnityFramework/UnityFramework.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
Could not build the precompiled application for the device.

Error launching application on iPhone.
Exited (sigterm)

To Reproduce

Steps to reproduce the behavior:

  1. Start a new flutter project - currently this specifies environment: sdk: ">=2.7.0 <3.0.0"
  2. Add flutter_unity: to dependencies: as per pub.dev installation instructions
  3. Build the example Unity project from this repo
  4. Follow all 6 steps here: https://github.com/Glartek/flutter-unity#ios-2
  5. Run

Expected behavior

Successful compilation and a default project loaded on iPhone

Additional context

Thanks for the awesome work on this, building fine on windows for android but can't get iOS to play ball.

I can successfully build and run the example project but cannot start a new project or add flutter_unity to an existing project successfully.

Mac OS: 10.15.5
Unity: 2019.3.7f1
XCode: 11.5
Visual Studio Code: 1.47.3

Fullscreen overridden

Describe the bug
I am not a 100% sure whether this is the plugin or something on my side.
The problem is that when I try do run my app full screen (which can be changed by the user, it's a setting) by running this code
SystemChrome.setEnabledSystemUIOverlays([]); the UnityView Widget automatically goes back to the original view.


  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([]);
    return Container(
      child: UnityView(
        onCreated: onUnityViewCreated,
        onReattached: onUnityViewReattached,
        onMessage: onUnityViewMessage,
      ),
    );
  }

The code above goes into full screen for a split second and then returns to regular view. If i replaced the code above with

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([]);
    return Container(
     color: Colors.brown,
    );
  }

(i.e. a brown container instead of a unity view) and perform a full restart, the app remains nicely in full screen mode so it's definitely working. When I exported my app in Unity > Resolution and Presentation > Start in fullscreen mode was set to false.

Additional context
Physical android device.

onMessage only being triggered once

Messages.send only gets caught once on the Flutter side of things, I have the UnityView widget in a screen of its own which I navigate to and from as needed but onMessage is only triggered the first time that the UnityView is opened

Do we need to import the Unity project inside Flutter project?

Describe the bug
Lack of Documentation
I found out that a Unity project exists inside the github repository of this plugin. You can search it inside this link. I tried to open this folder named: "FlutterUnityExample" in latest Unity free version and actually it is open and there is a cube inside. So, what I wanna know is, should we include our Unity project too inside[project-name]/unity/[Unity-project]by our self, or is it self-generated once we run this command below:
flutter pub run flutter_unity:unity_export_transmogrify

Logs freezes my Debug Build and make my App slower

Describe the bug
I encountered that in the native code sources the NSLog / logs are slowing down my builds. I don't know why it's needed to log anything, when we got message callback handlers in the flutter implementation?

Edit: My VSCode freezes after 1 min. And why aren't there a Loglevel.none or something? But it doesn't matter what you set. Logs are always the same...doesn't take effect...

To Reproduce
Steps to reproduce the behavior:

  1. Render a UnityView Widget
  2. Send messages in an interval of your choice (under 10 sec. interval) to Unity.

Expected behavior
No logs in native code, because we already have the choice in flutter

Screenshots
Bildschirmfoto 2020-11-17 um 21 30 20

Smartphone (please complete the following information):

  • Device: Android, iOS
  • OS: Android 11 (Target-API 29), iOS 14 (XCode 12)

Edit-edit: Wow, in Android it's full of Log.d's....

Error during flutter_unity build

Getting following error during the build.
All instructions were followed.
Xcode 13.1

ld: '/Users/minas.aslanyan/Library/Developer/Xcode/DerivedData/Runner-bilvcokkronqfgczapjdcycswzxw/Build/Products/Debug-iphoneos/UnityFramework.framework/UnityFramework' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. file '/Users/minas.aslanyan/Library/Developer/Xcode/DerivedData/Runner-bilvcokkronqfgczapjdcycswzxw/Build/Products/Debug-iphoneos/UnityFramework.framework/UnityFramework' for architecture arm64

Appreciate it if you can help with this.

Too much extra work before using the plugin on iOS. How about write the config in podspec and less extra work.

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when I use this plugin on iOS.

Describe the solution you'd like
I don't want to do the extra prebuild work on iOS before using this framework which is described in https://github.com/Glartek/flutter-unity#readme.
I suggest the framework should be built before I use this plugin. I don't want to build framework before I use this plugin.

Describe alternatives you've considered
Build the framework, make the framework become the depency of the plugin. Modify the podspec file in iOS folder to make everything automatic.

onReattached is undocumented, when does it trigger?

The UnityView has functions for 3 events/callbacks.

UnityView(
            onCreated: onUnityViewCreated,
            onReattached: onUnityViewReattached,
            onMessage: onUnityViewMessage,
            // key: 
          )

How or when is onReattached triggered?
I can't find it in either the example project or the Readme.

Running the example project on Android:
Every time you click the "test" button and enter the UnityViewPage, it will trigger onCreated.
The same happens on a second click when the unity loading screen doesn't show up.

unityViewController.pause() or unityViewController.resume() don't trigger it either.

Giving the UnityView a key:valueKey(..) and removing/adding the widget doesn't seem to change anything either.

Plugin Android setup problem

when i install the plugin via "pubspec.yaml", i got problem with jar file when i debug with android

Temporary Solution:
i clone the plugin locally and i copy my project inside the plugin project , no issues!!!!

Support bitcode

I'm using unity_flutter but I also need to compile with bitcode enabled. When bitcode is enabled, I get the following build error:

ld: -U and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together

This is a result of the setup requirements for this plugin where you have to add these linker flags:

-Wl,-U,_FlutterUnityPluginOnMessage

I understand that this is required to allow Unity to talk to iOS. Is there any way around this problem? I need to support bitcode because my app also has a WatchOS target, which requires that everything is bitcode.

How to get input touch in Unity?

How do you get Input.touches and Input.touchCount in Unity to work correctly? I would expect that if I tap on the Unity widget in Flutter that the touch would get transferred to Unity. But, in a script in Unity, I have an Update() method that simply runs Debug.Log(Input.touchCount); and it only prints 0, even when I am touching the Unity widget.
Did I set something up incorrectly, or does this not support passing touch inputs to Unity?

@rpath/Vuforia.framework/Vuforia not found for UnityFramework

After running the app in debug mode it quits immediately and throws an error.
I have followed the steps correctly and updated all the areas but I get the below error.

(lldb) dyld: dependent dylib '@rpath/Vuforia.framework/Vuforia' not found for '/private/var/containers/Bundle/Application/01E85DC2-3CCC-433C-B699-0D3FA2D3DFAD/Runner.app/Frameworks/UnityFramework.framework/UnityFramework', tried but didn't find: '/private/var/containers/Bundle/Application/01E85DC2-3CCC-433C-B699-0D3FA2D3DFAD/Runner.app/Frameworks/Vuforia.framework/Vuforia' '/usr/lib/swift/Vuforia.framework/Vuforia' '@rpath/Vuforia.framework/Vuforia' '/System/Library/Frameworks/Vuforia.framework/Vuforia'

iOS: version 10.0.3

What could cause this error?
Did anyone face this issue?

Linker issue/question - Undefined symbol: _FlutterUnityPluginOnMessage

I am trying to compile the example project running on Big Sur 11.2.1, Xcode 12.4, Flutter 1.22.6, Unity 2019.4.20f1

Just following the instructions with the example and I get:
Undefined symbol: _FlutterUnityPluginOnMessage
::
Undefined symbols for architecture arm64:
"_FlutterUnityPluginOnMessage", referenced from:
_Messages_FlutterUnityPluginOnMessage_mA8EF48D78A17E613D890457ACF4A0DF21A4E0853 in Assembly-CSharp.o
(maybe you meant: _Messages_FlutterUnityPluginOnMessage_mA8EF48D78A17E613D890457ACF4A0DF21A4E0853)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Steps to reproduce the behavior:
download the package zip file and follow the steps outlined. I get the error when trying to build the Runner project.

Detailed:

  • Build Unity project (2019.4.20f1) for iOS, save the build output to example/ios

  • Set /data folder target to UnityFramework (uncheck Unity-iPhone)

  • Open example/ios/runner.xcworkspace, "add to runner" and select Unity-iPhone

  • Modify build settings
    Enable Bitcode: No
    Unity-iPhone > Build Settings > Linking > other Linker Flags added:

-Wl,-U,_FlutterUnityPluginOnMessage

io.flutter.embedded_views_preview is already added and set to 1 in Runner/Info.plist

Build!
above Error :(

I saw that @artificerchris had this issue but resolved it with his linker settings - no such luck here.

Null safety

This package could need some updating. Will null-safety be supported in the near future?

FlutterUnityPlugin.Messages.Send failing in Release Build

The FlutterUnityPlugin.Messages.Send fails with ClassNotFoundException in Release Build.

It works fine in debug build.

Log

07-06 16:20:14.349 20359 20419 E Unity   : AndroidJavaException: java.lang.ClassNotFoundException: com.glartek.flutter_unity.FlutterUnityPlugin
07-06 16:20:14.349 20359 20419 E Unity   : java.lang.ClassNotFoundException: com.glartek.flutter_unity.FlutterUnityPlugin
07-06 16:20:14.349 20359 20419 E Unity   :      at java.lang.Class.classForName(Native Method)
07-06 16:20:14.349 20359 20419 E Unity   :      at java.lang.Class.forName(Class.java:454)
07-06 16:20:14.349 20359 20419 E Unity   :      at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
07-06 16:20:14.349 20359 20419 E Unity   :      at com.unity3d.player.UnityPlayer.access$300(Unknown Source:0)
07-06 16:20:14.349 20359 20419 E Unity   :      at com.unity3d.player.UnityPlayer$e$1.handleMessage(Unknown Source:83)  
07-06 16:20:14.349 20359 20419 E Unity   :      at android.os.Handler.dispatchMessage(Handler.java:103)                 
07-06 16:20:14.349 20359 20419 E Unity   :      at android.os.Looper.loop(Looper.java:214)
07-06 16:20:14.349 20359 20419 E Unity   :      at com.unity3d.player.UnityPlayer$e.run(Unknown Source:20)
07-06 16:20:14.349 20359 20419 E Unity   : Caused by: java.lang.ClassNotFoundException: com.glartek.flutter_unity.FlutterUnityPlugin

"UnityFramework/UnityFramework.h' file not found" when building for iOS

When building for iOS using Xcode 11.3.1, I get the following error which prevents build:

/Volumes/Data/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_unity-0.2.1+5/ios/Classes/FlutterUnityPlugin.m:3:9: 'UnityFramework/UnityFramework.h' file not found

My specs:
Flutter 1.20.4 stable
Xcode 11.3.1
Unity 2020.1.6

To Reproduce
Follow the exact steps in Readme to export a Unity project (using Unity v 2020.1.6) for iOS build, integrate into Flutter and configure iOS, then attempt flutter build ios

Things I've tried:

  • pod cache clean --all
  • cleaning Xcode build folder
  • flutter clean
  • manually adding the UnityFramework folder to Xcode header search paths

Web Support

Is it possible to have the same experience in web?

  • 3D?
  • AR/VR?

Is it possible to run dynamic scene

I run different scenes on my web application using react.js via webGL, but you know that webgl can not support the mobile browser.

I want to develop a mobile application to run the unity scenes dynamically.

Thanks to this library, i developed an application which runs a unity project, but i can not change the screen dynamically. Each scene is actually one unity project. Is it possible to dynamically run a unity project or scene or etc. via this library? So i have a lot of unity projects. Is it possible to run it dynamically in runtime, to download it from any url and to run inside a flutter application.

Thanks

Performance Impact

Hi, I just integrated a basic Unity Game into a Flutter app. All I can do is move a gameObject using my finger.

I've noticed a lower frame rate compared to the standalone apk from Unity. Tests have been done in release mode on Android.

I must admit, I'm worried about the future, once the Unity game gets bigger. I'd also love to increase the current FPS.

Looking at the issues from this package or this one, no one seems to complain about it. Did I miss something ?

Could not find and invoke the GeneratedPluginRegistrant

After Build finishes and installing the app I always get this message:
W/FlutterActivity(11083): Tried to automatically register plugins with FlutterEngine (io.flutter.embedding.engine.FlutterEngine@f7afde) but could not find and invoke the GeneratedPluginRegistrant.

And I think as a result of that the plugin doesn't work and I get this exception
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'android.view.ViewParent com.glartek.flutter_unity.FlutterUnityPlayer.getParent()' on a null object reference, null)

To Reproduce
flutter run

Output of Flutter doctor
flutter doctor -v
[√] Flutter (Channel stable, 1.20.3, on Microsoft Windows [Version 10.0.18362.1139], locale en-US)
• Flutter version 1.20.3 at D:\flutter
• Framework revision 216dee60c0 (10 weeks ago), 2020-09-01 12:24:47 -0700
• Engine revision d1bc06f032
• Dart version 2.9.2
• Pub download mirror https://pub.dartlang.org
• Flutter download mirror https://storage.flutter-io.cn

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
• Android SDK at C:\Users\Bcc\AppData\Local\Android
• Platform android-29, build-tools 29.0.2
• ANDROID_HOME = C:\Users\Bcc\AppData\Local\Android
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
• All Android licenses accepted.

[√] Android Studio (version 3.4)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 39.0.1
• Dart plugin version 183.6270
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

[√] VS Code (version 1.51.0)
• VS Code at C:\Users\Bcc\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.16.0

[√] Connected device (1 available)
• Android SDK built for x86 (mobile) • emulator-5554 • android-x86 • Android 8.1.0 (API 27) (emulator)

• No issues found!

Is there anything that can make this happen? and how to fix it?

References to platform views lost in iOS due to gViews being reinitialised

I've been having problems where messages from Unity to iOS stop being received. This seems to happen if I have multiple UnityView widgets on the flutter side, and I navigate between them. I've done some digging and found a problem - the following function in FlutterUnityPlugin.m is called multiple times:

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    UfwLoad();
    gViews = [[NSMutableArray alloc] init];
    FlutterUnityViewFactory * viewFactory = [[FlutterUnityViewFactory alloc] initWithMessenger: [registrar messenger]];
    [registrar registerViewFactory: viewFactory withId: @"unity_view"];
} 

This means that when this function is called the second or subsequent times, the gView variable is reinitialised, and so any references to views created by the viewfactory are lost. I think this is why my messages suddenly step being received by flutter - Unity is passing messages to iOS, but iOS no longer sends them to the UnityView in flutter because it doesn't have references to the views. Specifically, when it goes around this loop:

 for (FlutterUnityView * view in gViews) {
            if ((int64_t)messageId < 0 || (int64_t)messageId == [view viewId]) {
                [view onMessage: messageData];
            }
        }

It does not find all the views. I suspect this is also the cause of this possibly related issue.

I would suggest that a check is added to only initialise gViews if it is 'nil'?

Can't build Android anymore after adding this plugin

Describe the bug
I tried to build with and without this plugin my android project, but whenever I add this plugin, my Flutter Android App is not recognizing any Plugin anymore.

To Reproduce
Steps to reproduce the behavior:

  1. Follow the steps for android in the readme.
  2. Add flutter_unity to your pubspec.yaml.
  3. Add path_provider to this project!!
  4. Try to debug or release run

Expected behavior
My Plugins are recognized when using this plugin.

Smartphone (please complete the following information):

  • Device: Android
  • OS: 10 (API 29)
  • Unity: 2019.3.*
  • Flutter 1.21.0

Error

✓ Built build/app/outputs/flutter-apk/app-debug.apk.
W/FlutterActivity( 9776): Tried to automatically register plugins with FlutterEngine (io.flutter.embedding.engine.FlutterEngine@30d59d2) but could not find and invoke the GeneratedPluginRegistrant.
Connecting to VM Service at ws://127.0.0.1:51373/VZI-WrkSf1Y=/ws
E/flutter ( 9776): [ERROR:flutter/lib/ui/ui_dart_state.cc(171)] Unhandled Exception: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
E/flutter ( 9776): #0      MethodChannel._invokeMethod 
package:flutter/…/services/platform_channel.dart:158
E/flutter ( 9776): <asynchronous suspension>
E/flutter ( 9776): #1      MethodChannel.invokeMethod 
package:flutter/…/services/platform_channel.dart:333
E/flutter ( 9776): #2      MethodChannelPathProvider.getApplicationDocumentsPath 
package:path_provider_platform_interface/src/method_channel_path_provider.dart:50
E/flutter ( 9776): #3      getApplicationDocumentsDirectory 
package:path_provider/path_provider.dart:109
E/flutter ( 9776): #4      AppService.init 
package:app/app/service.dart:24
E/flutter ( 9776): #5      main 
package:app/main.dart:20
E/flutter ( 9776): #6      _runMainZoned.<anonymous closure>.<anonymous closure>  (dart:ui/hooks.dart:233:25)
E/flutter ( 9776): #7      _rootRun  (dart:async/zone.dart:1190:13)
E/flutter ( 9776): #8      _CustomZone.run  (dart:async/zone.dart:1093:19)
E/flutter ( 9776): #9      _runZoned  (dart:async/zone.dart:1630:10)
E/flutter ( 9776): #10     runZonedGuarded  (dart:async/zone.dart:1618:12)
E/flutter ( 9776): #11     _runMainZoned.<anonymous closure>  (dart:ui/hooks.dart:225:5)
E/flutter ( 9776): #12     _startIsolate.<anonymous closure>  (dart:isolate-patch/isolate_patch.dart:301:19)
E/flutter ( 9776): #13     _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter ( 9776):
Exited

Pod install error

when I pod install ,there error for this. How Can I do it?

$ pod install
Invalid plugin specification: EXCLUDED_ARCHS[sdk=iphonesimulator*]=i386

[!] Invalid Podfile file: no implicit conversion of nil into String.

from /Users/yyw/Desktop/FlutterDemo/unityFlutter/flutter-unity/example/ios/Podfile:54

-------------------------------------------

unless File.exist?(copied_framework_path)

   FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir)

end

-------------------------------------------

Some libraries are not integrated when compiling the application in production mode

Basically I am using the library to place a virtual reality application (cardboard) within an application written in Flutter, when debugging the app in development or compiling a debug apk it works without problem, but when compiling the application to launch it The production does not compile well and ends up compiling the app without the virtual reality functionality, I have tried to find the error or change when it is compiled, but I have not found anything relevant, I have read and followed the guide many times, even without success.

(This is my first issue, if you need more information or anything I will be here)

View on debugging app:
WhatsApp Image 2020-10-12 at 8 45 45 PM

View on release app:
WhatsApp Image 2020-10-12 at 8 45 58 PM

Restart unity player

Hello there,

I would like to restart the unity player each time the widget UnityView is rendered, a simple example would be :

  • I navigate into a widget with UnityView
  • Play a game
  • Navigate out of the widget with UnityView
  • Come back later to the widget with UnityView and have a fresh start

Current behaviour : when the UnityView is recreated, the game is at the last state it was in.
Am I missing something ?

Thanks in advance.

Setup instructions need updating for latest Unity version

I followed the exact setup instructions for flutter_unity, however I got a build error which I think is due to the fact that the export format has changed in the latest Unity (I'm using version 2020.1.2f1):

FAILURE: Build failed with an exception.

* Where:
Build file 'D:\MyFlutterProject\android\unityExport\build.gradle' line: 85

* What went wrong:
A problem occurred configuring project ':unityExport'.
> Project with path ':unityLibrary' could not be found in project ':unityExport'.

It looks like the android/unityExport/build.gradle file (which is generated when exporting the unity project) has changed, because it doesn't match the one found in the example project. Specifically, there is all this extra stuff at the end of the file:

def getSdkDir() {
    Properties local = new Properties()
    local.load(new FileInputStream("${rootDir}/local.properties"))
    return local.getProperty('sdk.dir')
}

def BuildIl2Cpp(String workingDir, String targetDirectory, String architecture, String abi, String configuration) {
    exec {
        commandLine(workingDir + "/src/main/Il2CppOutputProject/IL2CPP/build/deploy/net471/il2cpp.exe",
            "--compile-cpp",
            "--libil2cpp-static",
            "--platform=Android",
            "--architecture=" + architecture,
            "--configuration=" + configuration,
            "--outputpath=" + workingDir + targetDirectory + abi + "/libil2cpp.so",
            "--cachedirectory=" + workingDir + "/build/il2cpp_"+ abi + "_" + configuration + "/il2cpp_cache",
            "--additional-include-directories=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/external/bdwgc/include",
            "--additional-include-directories=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/libil2cpp/include",
            "--tool-chain-path=" + android.ndkDirectory,
            "--map-file-parser=" + workingDir + "/src/main/Il2CppOutputProject/IL2CPP/MapFileParser/MapFileParser.exe",
            "--generatedcppdir=" + workingDir + "/src/main/Il2CppOutputProject/Source/il2cppOutput",
            "--baselib-directory=" + workingDir + "/src/main/jniStaticLibs/" + abi,
            "--dotnetprofile=unityaot")
        environment "ANDROID_SDK_ROOT", getSdkDir()
    }
    delete workingDir + targetDirectory + abi + "/libil2cpp.sym.so"
    ant.move(file: workingDir + targetDirectory + abi + "/libil2cpp.dbg.so", tofile: workingDir + "/symbols/" + abi + "/libil2cpp.so")
}

android {
    task BuildIl2CppTask {
        doLast {
              BuildIl2Cpp(projectDir.toString().replaceAll('\\\\', '/'), '/src/main/jniLibs/', 'ARMv7', 'armeabi-v7a', 'Release');
              BuildIl2Cpp(projectDir.toString().replaceAll('\\\\', '/'), '/src/main/jniLibs/', 'ARM64', 'arm64-v8a', 'Release');
        }
    }
    afterEvaluate {
        if (project(':unityLibrary').tasks.findByName('mergeDebugJniLibFolders'))
            project(':unityLibrary').mergeDebugJniLibFolders.dependsOn BuildIl2CppTask
        if (project(':unityLibrary').tasks.findByName('mergeReleaseJniLibFolders'))
            project(':unityLibrary').mergeReleaseJniLibFolders.dependsOn BuildIl2CppTask
    }
    sourceSets {
        main {
            jni.srcDirs = ["src/main/Il2CppOutputProject"]
        }
    }
}

The problem is the afterEvaluate block. I managed to resolve the error by changing this reference to unityLibrary:

    afterEvaluate {
        if (project(':unityLibrary').tasks.findByName('mergeDebugJniLibFolders'))
            project(':unityLibrary').mergeDebugJniLibFolders.dependsOn BuildIl2CppTask
        if (project(':unityLibrary').tasks.findByName('mergeReleaseJniLibFolders'))
            project(':unityLibrary').mergeReleaseJniLibFolders.dependsOn BuildIl2CppTask
    }

to unityExport:

    afterEvaluate {
        if (project(':unityExport').tasks.findByName('mergeDebugJniLibFolders'))
            project(':unityExport').mergeDebugJniLibFolders.dependsOn BuildIl2CppTask
        if (project(':unityExport').tasks.findByName('mergeReleaseJniLibFolders'))
            project(':unityExport').mergeReleaseJniLibFolders.dependsOn BuildIl2CppTask
    }

Perhaps this change should be added to the documentation, OR the setup instructions should be changed to specify that the export directory name should be unityLibrary instead of unityExport so that this change isn't needed?

Flutter unity_export_transmog command fail

Describe the bug
After install the plugin, i try to run this command as said in the documentation:
flutter pub run flutter_unity:unity_export_transmog

Got this output:
Could not find bin/unity_export_transmog.dart in package flutter_unity.

To Reproduce
Steps to reproduce the behavior:

  1. intall the plugin
  2. Run this command : flutter pub run flutter_unity:unity_export_transmog
  3. See error

[IOS]: App crashing before first platform view

Describe the bug
I can successfully build iOS, but when I run my app, my view is not appearing and immediatly my app is crashing with the screenshot underneeth.

To Reproduce
Steps to reproduce the behavior:

  1. Build with unity for IOS.
  2. Follow readme instructions for integrating iOS build
  3. try to debug/run your ios app on an iphone or ipad.

Expected behavior
UnityFramework is not crashing.

Screenshots
Bildschirmfoto 2020-08-16 um 00 03 03

Smartphone (please complete the following information):

  • Device: IOS
  • OS: 13
  • XCode: 11
  • Unity: 2019.3.*

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.