Switch input handlers in Unity

In this tutorial we will learn a simple and efficient way to change the input handlers in Unity3D using a UI Button. You can use this in your game menu settings if you want to let users change between different input handlers. This can be also very helpful if we want to port a game from mobile to PC and you still want to keep the logic behind your inputs.

Let’s consider that we have 3 types of input handlers that we want in our game and we want to change them maybe from a settings menu using only one button.

Input handlers:

Keyboard

Mouse

Accelerometer

If we want to change them without headaches we can create an interface called IInput which is going to be implemented by our handlers.

Input handlers

Let’s create the IInput interface. For the moment we have only one dummy method called GetAxis which returns a Vector3 but you can add more methods if you want.

As you can see all these classes don’t derive from MonoBehaviour, we don’t want to attach them to any GameObject.

Finally, to show how this thing works, we need to create a script called Button_Input_Settings which we will attach to our UI button from Unity3D. Here we have a method OnClick() which is called when we press on the button. In this method we decide what input handler we are going to use:

I have been working as a software engineer in computer graphics for almost 5 years. In the free time I love playing guitar, playing video games, hiking and studying computer graphics techniques.Follow me on : Google + , Twitter, Facebook