GithubHelp home page GithubHelp logo

mopsicus / umi Goto Github PK

View Code? Open in Web Editor NEW
365.0 19.0 87.0 2.39 MB

Unity mobile input (UMI) plugin for Android and iOS, allows to use features of mobile native input fields

License: MIT License

Java 15.97% Objective-C 1.33% Objective-C++ 13.20% C# 32.96% ShaderLab 31.13% HLSL 5.41%
unity3d native-module plugins plugin-system assets unity ios android inputfield textarea

umi's Introduction

Static Badge Static Badge

UMI (UnityMobileInput)

UMI

Unity plugin for Android and iOS, allows to use features of mobile native input fields

Quick start · Documentation · Report Bug

💬 Overview

This package allows you to use native input fields on Android and iOS. It works with TMP InputField component and uses some of its options.

Problem

The current implementation of Unity's input field doesn't allow you to use selection, copy/paste, emoji, and other built-in features on mobile. And no one knows when that will happen or if it will happen at all.

Solution

This plugin creates native input fields above the canvas UI with all platform features. Since this is a hack and the input fields are placed above the UI, you will have to control their visibility and position yourself. The plugin provides some useful options to make this more convenient.

✨ Features

  • native input field and keyboard on iOS and Android
  • select return button type: Default, Next, Done, Search, Send
  • control return button callback
  • control Done and Clear buttons (iOS)
  • change some options in runtime
  • hiding additional mobile input box (Android)
  • detect keyboard show/hide (with height)
  • detect screen orientation
  • custom fonts support

🚀 Usage

Installation

Get it from releases page or add the line to Packages/manifest.json and module will be installed directly from Git url:

"com.mopsicus.umi": "https://github.com/mopsicus/umi.git",

Quick start

See the samples section to get a demo app. This demo will show you how to initiate and use UMI in your app, how to create a chat-like app, and how to use a custom font.

Tested in Unity 2020.3.x, Android (API >= 24) and iOS.

Initialization

Before creating the first input field, UMI must be initiated. It should create a special game object on the scene with a controller that will interact with native plugins.

To do this, add UMI to the uses section and call the init method, for example, in the Awake method in your app's entry point.

using UnityEngine;
using UMI;

public class Bootstrap : MonoBehaviour {

    void Awake() {
        MobileInput.Init();
    }
    
}

Note

Make sure you do this before creating all input fields, otherwise UMI will raise an exception.

Setup

To begin using UMI in your project, add MobileInputField script to game object with TMP Input field.

In the inspector, you can edit several options that will be applied to the native input field:

  • text color
  • placeholder text
  • placeholder text color
  • character limit
  • font size
  • text align
  • content type
  • input type
  • keyboard type
  • multiline option

From UMI, you can edit these additional options:

  • background color
  • return button type
  • return button callback
  • custom font
  • manual hide option
  • done & clear buttons option

Keyboard and orientation callbacks

If you need to detect the appearance or hiding of the keyboard, you must subscribe to events and add a handler to your code.

using UnityEngine;
using UMI;

public class Bootstrap : MonoBehaviour {

    void Awake() {
        MobileInput.Init();
        MobileInput.OnKeyboardAction += OnKeyboardAction;
        MobileInput.OnOrientationChange += OnOrientationChange;
    }

    void OnOrientationChange(HardwareOrientation orientation) {
        // raise when the screen orientation is changed
    }

    void OnKeyboardAction(bool isShow, int height) {
        // raise when the keyboard is displayed or hidden, and when the keyboard height is changed
    }
    
}

With OnKeyboardAction you can control UI elements, such as moving the input field as in chat apps. See the demo app.

Runtime methods

  • SetTextColor – change text color
  • SetPlaceholderColor – change placeholder text color
  • SetBackgroundColor – change background color
  • SetContentType – change input field content type
  • SetReadonly – change readonly mode

How to use custom fonts

  1. Copy TTF fonts to StreamingAssets folder
  2. Input font name in property instead default
  3. Profit

When you first initialize, UMI will copy the fonts to a special app folder for your use. If you change the font(s) on the next update, you'll have to call MobileInput.UpdateFonts() to update the app folder with the fonts.

iOS

The iOS plugin is simple, with only 3 files. If you want to know how it works under the hood - look for the MobileInput.mm file in the Plugins folder of the package and read the docs.

Android

Android plugin is a compiled AAR library. All sources are available in Android~ folder. You can edit the android part and recompile the library to suit your needs.

Make sure your AndroidManifest.xml has the following setting:

<activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name" android:windowSoftInputMode="adjustNothing">
    ...
    <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
    ...
</activity>

The adjustNothing option has been added to prevent the screen from shifting up when the keyboard is displayed.

Unity

The Unity part contains a wrapper to call the native methods of the input field and an editor script to customize the parameters in inspector.

At initialization, the plugin creates a non-destructible game object for sending and receiving commands from the native part. When the MobileInputField script is used, the plugin registers it and creates a native field.

Data passed between the Unity app and native plugins is in JSON format. UMI uses NiceJson library for this purpose with some modifications.

🏗️ Contributing

We invite you to contribute and help improve UMI. Please see contributing document. 🤗

You also can contribute to the UMI project by:

  • Helping other users
  • Monitoring the issue queue
  • Sharing it to your socials
  • Referring it in your projects

Environment setup

For a better experience, you can set up an environment for local development. Since UMI is developed with VS Code, all settings are provided for it.

  1. Use Monokai Pro or eppz! theme
  2. Use FiraCode font
  3. Install extensions:
    • C#
    • C# Dev Kit
    • Unity
  4. Enable Inlay Hints in C# extension
  5. Install Visual Studio Editor package in Unity
  6. Put .editorconfig in root project directory
  7. Be cool

🤝 Support

You can support the project by using any of the ways below:

  • Bitcoin (BTC): 1VccPXdHeiUofzEj4hPfvVbdnzoKkX8TJ
  • USDT (TRC20): TMHacMp461jHH2SHJQn8VkzCPNEMrFno7m
  • TON: UQDVp346KxR6XxFeYc3ksZ_jOuYjztg7b4lEs6ulEWYmJb0f
  • Visa, Mastercard via Boosty
  • MIR via CloudTips
  • Paypal

✉️ Contact

Before you ask a question, it is best to search for existing issues that might help you. Anyway, you can ask any questions and send suggestions by email or Telegram.

🔑 License

UMI is licensed under the MIT License. Use it for free and be happy. 🎉

umi's People

Contributors

bgamepoint avatar filipvajgand avatar henriquesabino avatar mops avatar mopsicus avatar prisedrabbit avatar rthery avatar soprachevak avatar strider2k 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

umi's Issues

Can't click on Anything else

I'm using Unity 2017.4.2f2

The problem is, the plugin is working fine but it doesn't let me click anything else in the scene, although I've placed other stuff on top of it in hierarchy.

Please let me know how to solve this issue cuz it's is a big put down.

when keyboard showed,the height value is wrong。

i use canvas mode is "Screen Space - Camera", and i set the camera's size to 3.2.
then i notice when keboard showd on my ipad(20481536) , the keyboard size is (x=0,y=310,width=1024,height=458), so the size is 1024768....while not 2048*1536 screen size.

White box over Input Field and no Text.

When I build my project for Android, a white box appears over my Input Field.

Images are here:
https://imgur.com/a/v2y5hMh

I ran the project you provided from this GitHub and built it for android, and everything worked perfectly as expected.

But upon setting up my own project to work for this input method, it didn't work as expected.

I can provide further details if you need, I'm sure it's just a "check box" somewhere that I didn't press, but I've tried almost everything now.

I switched my graphics and rendering settings around.
I using Text Mesh Pro instead of the default Text component,
Used different graphics API.
Changed my camera settings, and Canvas rendering.

I am using Unity 2018.3.0f2.

If there's any other information needed to figure out this problem, I'd be happy to provide. This has been a huge problem for me for weeks.

Java source code

Do you mind adding the source code of the mobileinput-release.aar to this repository? This would be very helpful for adding custom features. Thank you!

Customize input on runtine is not working

I have a very specific usecase, I'm using the same keyboard on different layer but with different properties.
1st Layer: The input field should be limited to 25 characters, no specific content type.
2nd Layer: The input field should be limited to 6 characters, only caps lock and letters.

After trying to find a workaround, it seems you create from scratch a new android keyboard based on the original one attached to the GameObject.
Then I can't find any access on unity side to change the properties I listed on runtime.

Did I miss or misunderstood something ?

Thank you in advance.

Change native field font

Is it possible to change the font/style of the native input field?
Style meaning bold, italics, etc.

How Change Font

always fonts are arial..how could I change it to something else....in android

Disable Input Field

Hi, is there a way to disable the input?

I tried :
mobileInput.InputField.interactable = false;

But but does not seem to work.
Any ideas?

Thanks!

Alignement On IOS

Hello,

I am having problems with IOS 12 on an Iphone 8 where the Text Input fields are not lining up correctly. On Android, the text box is correct.
This is what I am getting on the Iphone. The text is centered.
Image-1
This is what I am getting on the Android. The text is aligned to the left. This is what I am looking to achieve on IOS as well.
thumbnail

All the settings seem to be correct. Any idea if this is related to IOS native?

Thank you for your time

Проблема дублирования файлов

Привет, при установке вашего плагина возникает много ошибок вида:
Found plugins with same names and architectures, Assets/Plugins/UnityMobileInput-master/Android/UnityMobileInput/app/src/test/java/ru/mopsicus/unitymobileinput/ExampleUnitTest.java () and Assets/Plugins/UnityMobileInput-master/Android/UnityMobileInput/common/src/test/java/ru/mopsicus/common/ExampleUnitTest.java (). Assign different architectures or delete the duplicate.
Не подскажете, как это можно исправить?
P.S. ошибки возникают на вашей же демо-сцене, ничего туда не добавлял

Getting exception when I play it in Editor

EntryPointNotFoundException: pluginsInit
Mopsicus.Plugins.Plugins.InitPlugins () (at Assets/Plugins/UnityMobileInput/Unity/Assets/Scripts/UnityMobileInput/Plugins.cs:101)
Mopsicus.Plugins.Plugins.Awake () (at Assets/Plugins/UnityMobileInput/Unity/Assets/Scripts/UnityMobileInput/Plugins.cs:77)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Strange behaviour with Scroll Rect

When I add the the Input Fields in the Demo scene to a Scroll Rect they exhibit this strange behaviour of the white image and text staying in the position they were in when the native keyboard was opened.

Screenshot_20190918-140828_q-cells

Simultaneous interaction

Hi, I want to be able to interact with my application while the keyboard is open. For example I want to be able to click on a button while the keyboard is open, the current state of the plugin (and unity TouchKeyBoard) makes the app lose focus when It is visible, thus you need to click twice on the screen before being able to click on a button, any solutions ?
Thanks

OnSelect / OnDeselect events aren't fired

These events aren't fired at least on Android. You should be able to catch them by placing a script on the field GameObject which implements UnityEngine.EventSystems.ISelectHandler.
We need this to scroll the UI up when user selects a field so that it's not covered by the keyboard.

Prevent keyboard auto-hide

Trying to implement messenger chat I need to prevent keyboard auto-hide to allow user click "Send" button. Unfortunately, keyboard closes on any screen space tap.
How can I modify it?

On Android 4.4 icons not visible

On Android 4.4 icons like copy/paste/cut is white and background is white too. Can i fix it by set custom color to this icons? How?
And one more: caret is not visible

Can't get masked by a unity mask component

I added an Input field in a scroll view and when I scroll down or up the input field is always displaying. How can I fix this problem.
PS the plugin is epic! Just need to fix this problem and all would be good Thx in advance

MobileInputHandler.cs's OnData() was not being called

On iOS with Unity 2018.1.1f1.

MobileInputHandler.cs's OnData() was not being called.
But Plugin.cs's OnDataReceive() was being called.
It seems it was being blocked out by the below if statement.

if (plugin.Name == info["name"])

So I changed MobileInputHandler.cs's Name to return "MobileInputHandler".
I don't know it this was the proper way to fix this, but it works fine now.

By the way, I love this plugin. I really needed this.
Thank you.

InputField Visibility trouble

I have a bug: my Plugin object locate in my global obj and after run - he become DontDestroyOnLoad's object, it's all right, but my InputField object locate in other object, for instance "Ghoul" which is inactive from the start, when I open this "Ghoul" it's also all right, it works perfectly.
Thing is, when I close this Ghoul and switch from my app to youtube, for instance, and switch back to my app and enable Ghoul - I saw that no InputField exist because he is still invisible. It's impossible to fix this by enabling/disabling Ghoul or any other object. But when I close Ghoul and switch my app to youtube again, switch back and enable Ghoul - InputField become visible again. How it can be fixed? I have no idea, when I tried to check in Update the visibility state - I saw false, but InputField was visible. I have to this bug be fixed as soon as possible.
Help me please....

Keyboard not showing iOS

Hi all,

I have an issue, a user contacted us,
an iOS user ( iPad )

Keyboard is not showing at all, based on screenshots sent, I can see that input fields are hidden.

it happens sometimes with me but I can't easily reproduce it, it just happens by itself.

but with that user it always happens

Any thoughts how to debug this issue with the user ?

Thanks

ContentSizeFitter not working

I can't understand, why adding the text my input field doesn't fix it's sizing, while I got ContentSizeFitter and VerticalLayoutGroup components. It works well with native Unity Touch Keyboard activation, but doesn't with this plugin usage. I tried to call add canvas update

/// <summary>
        /// Text change callback
        /// </summary>
        /// <param name="text">new text</param>
        private void OnTextChange(string text)
        {
            if (text == this._inputObject.text)
            {
                return;
            }

            this._inputObject.text = text;
            if (this._inputObject.onValueChanged != null)
            {
                this._inputObject.onValueChanged.Invoke(text);
            }
            
            _inputObject.ForceLabelUpdate();
            Canvas.ForceUpdateCanvases();
        }

but nothing works. Why so? How can I fix it?

XR mode issue

Hello,
When the device comes back from cardboard, disappear text input.

in cardboard
XRSettings.LoadDeviceByName("cardboard");

exit cardmode
XRSettings.LoadDeviceByName("None");

disappear text input.

Iphone keyboard height return not in pixel.

Для Iphone 11, X возвращается одинаковая высота, насколько я понял(по андроиду и логике) нужно возвращать в пикселях экрана.
Все дело в том что height возвращает в points

#33

TextMeshPro and UnityMobileInput

Hey,

is there a way to use this with TextMeshPro? I changed all occurences of InputField and Text to TMP_InputField and TMP_Text. It basically works, but font size and alignment (maybe some more features) are wrong. Does anybody know why? :)

Martin
UnityMobileInput_issue

OnShowKeyboard no trigger

there is a slight problem, when you switch to another scene and return to the input scene the OnShowKeyboard function is not called.

RTL Problem when we use this plugin

Unity Game Engine RTL Support :https://github.com/ElectroGryphon/EGGA/tree/master/UPersian

when I use above plugin to enable rtl support

and then ur plugin

the input field from transparent turn to white image that rtl texts havebeen flipped

and just ur keyboard workds perfectly and other plugin do wrong job.


I review ur scripts and it seams in android u create an input field urself and hide original one...so the new one has a white background and doesnot support rtl ...that the point that makes problem...:(
I can fixed white back but rtl support still has problem with ur procedure..:)


One solution for this situation is : use above rtl plugin directly but change Placeholder -rtl component with normal Text component .and in android automatically it will shows correctly... for pc version we should not remove anything it works perfect.....

for bg

in mobileinput script we should find where u changed background and set it to anything we want....

thank you for ur plugin and ur efforts ...<3

KeyboardHeight not right in some device

I test my demo in Rog phone. Resolution is 2340 * 1038. I want to change my component according to soft Ketboard Height ,but the value is not right , try mate30 is so . samsung s7 is right , Very strange

Other UGUI components are obscured by the android native input box

I set up an information entry interface which contains InputField and Dropdown box. However, when I click on the Dropdown box, I notice that the Dropdown box is obscured by the android native input box. I try to adjust their layer but it doesn't work. How should I handle this situation?

拖动无法移动

添加到ScrollView之后,ScrollView自己滑动的时候,可以一起移动。
拖动ScrollView的时候,控件无法和ScrollView一起移动。有办法解决拖动的问题吗?

iPad external keyboard don't working

It seems physical keyboard not working for all UnityNativeEdit forks. I tried this for different repos.
When a keyboard connected to the iPad, screen keyboard hides, and physical buttons on the external keyboard don't do anything.
But the screen keyboard itself works well for the same build.
Would you like to fix this issue? I can provide any possible help.

На всякий случай напишу на русском. У меня стандартная клавиатура для айпада от эпла, которая в виде чехла-накладки. Но почему-то инпут филд на нее реагирует плохо. Иногда символы появляются, иногда нет. Пробел и смена языка - не работают совсем.
В остальном - плагин работает отлично. С экранной клавиатуры можно вводить текст без нареканий.
Такие же глюки есть в крупном приложении Yousician, эти ребята использует свою версию UnityNativeEdit. Видимо все это семейство форков физическую клавиатуру не подерживает.
Я сейчас делаю проект на юнити и могу помочь с тестами, или помочь с кодом. Скорее всего там достаточно будет небольшой доработки.

Adding "Social" option for keyboard

Would be great to add social keyboard to be called as well.
Similar to this Unity method:
_keyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Social, true, false, false);
This also add the suggested words on a top of the keyboard.

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.