Tip Of the Day: Input on Mobile Unity2D
So you have finished your project or prototype on your PC/Mac and you want to allow your player to move on his mobile device. How would you do that?
If you are still not using the new Input Manager in Unity, then there is a quick and easy way to do it, and here is how you do it using Unity’s Cross Platform Input.
A. Download Standard Assets
Go to Standard Assets (for Unity 2018.4) | Asset Packs | Unity Asset Store, and add the asset to your assets. In Unity, open your package manager and switch to “My Assets” and fine the Standard Assets, download it and press import.
You do not need to import everything, if you want you can just import everything related to “CrossPlatformInput”.
B. Add the Joystick UI to your game
Now that you have the Standard Assets in your assets folder, go to Assets / Standard Assets / CrossPlatformInput / Prefabs and drag into your scene the “MobileSingleStickControl”. Add to your UI and make sure it is the last item in your UI so it does not get blocked by other UI elements
The prefab will a Joystick and a jump button. Now you can change the joystick and button sprites to whatever you want and also add more buttons.
C. Code Implementation
In the script that handles your player Input, firstly and most importantly you need to add the namespace “using UnityStandardAssets.CrossPlatformInput;”. This will give you access to the cross platform input manager.
For the joystick, just like you would get the axis from unity’s input manager you would do the same for your horizontal and vertical inputs for the CrossPlatformInput.
_xHorizontal = CrossPlatformInputManager.GetAxisRaw("Horizontal");
In my case I wanted to control the horizontal movement, so I accesses the GetAxis from the CrossPlatformInputManager.
As for the buttons, each button in the MobileSingleStickControl has a ButtonHandler script with a name variable that you can change and program it as your input.
In my case, I renamed my 1st button to A_Button.
In order to use the button, we will use following code
The same way you would register for a button press on your keyboard.
This way you can program more buttons into your game.
This is how it looks in my project: