Skip to main content

How to add a Virtual Button in an android game


Simple Steps to add a virtual button an android

1. Download and Import Unity Standard Assets from here...
 -For this functionality we only need the CrossPlatformInput and Editor assets. Make sure to import both of them
 -Make sure that android is selected in your File>Build settings menu
 -Make sure that Mobile Input is Enabled in the Editor


2. Right click in your scene hierarchy and go to UI>Button
Step 2
 -A canvas and an event system will be created automatically
 (If you don't know what these mean, don't worry)

3. Align the button on the canvas according to your liking.
Step 3
 -Think of the canvas as the screen of the device on which your game is supposed to run on

4. Rename the Button, apply sprites and customize it as per your liking.
 - This step is not super important if you just want the functionality. It can be done later on as well

5. Click and Drag the ButtonHandler script from Assets>Standard Assets>CrossPlatformInput>Scripts folder to the button you just created.
Step 5

6. Go to Edit>Project Settings>Input.
Step 6

7. Increment the Size value by one and to the last entry add your custom button name. And nullify all the other value.

8. Add the same custom name to your button's Button Handler (Script)
 -In my case it is "xlr8"...
Step 8

9. Create a script and add a namespace reference -> using UnityStandardAssets.CrossPlatformInput;

10. Write the code for what the button should do under this-
 if(CrossPlatformInputManager.GetButton("button_name") //In my case button_name is xlr8
 {

  //Your code goes here
 }
 - You can use GetButtonDown() or GetButtonUp() methods as well

11. Apply the script to appropriate game object

12. Now Select Canvas>Button from scene hierarchy click Add Component>Event>Event Trigger>Add New Event Type>Pointer Down
Step 12

13. Click the + sign in "Event Trigger (Script)" Panel

14. Click and drag the button from scene hierarcht to Pointer Down Panel.
Step 14

15. Click No Function>ButtonHandler>SetDownState ()

16. Repeat step 12, 13, 14 and 15 but this time, Add Pointer Up and Select SetUpState ()

17. Done!!! The button should work as expected now. Test it out using unity remote app
 -If you dont know how to do that, click here...








Comments

  1. Thanks a lot!Will test and get back if issues.

    ReplyDelete
  2. Worked perfectly!Thank you again for your tutorial.

    ReplyDelete

Post a Comment