Input functionality across PC and Mobile made easy!
Unity has a free standard asset pack available in the asset store that contains cross-platform input functionality that we can all use.
It’s called “Standard Assets.” Once downloaded, import only the “CrossplatformInput” and “Editor” folders.
In the CrossPlatformInput folder, there are prefabs available to us on the go. Since I am currently developing a 2D mobile platform game, I will drag the “MobileSingleStickControl” prefab to the Hierarchy.
The prefab will automatically place UI elements for the game. A joystick and a button. I changed the images to them and added a second button. When hitting the play button, they are intractable.
For the buttons, I made sure through the inspector to have a name for them. Here’s an example of the A button:
I named it Attack. I will then call this “Attack” through code.
In the player script, where I have my movement logic, I added
using UnityStandardAssets.CrossPlatformInput; as a namespace, and I replaced:
float xMove = Input.GetAxisRaw(“Horizontal”);
float xMove = CrossPlatformInputManager.GetAxis(“Horizontal”);
The GetAxis for the CrossPlatformInputManager will provide movement behavior for the computer and mobile devices.
I can now replace all the input to use
CrossPlatformInputManager or add them with the regular input that is already there.
The B button will be for jumping:
if (Input.GetKeyDown(KeyCode.Space) || CrossPlatformInputManager.GetButtonDown(“Jump”) && _isGrounded)
_enableJump = true;
The A button will be for attacking:
if (Input.GetKeyDown(KeyCode.Mouse0) || CrossPlatformInputManager.GetButtonDown(“Attack”) && _isGrounded && !_isAttacking)
With all of this set, I now have a working input system for mobile!