Home Game Development Unity Game Development Scripting

Unity Game Development Scripting

By Kyle D'Aoust
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Interactive Input
About this book
Publication date:
December 2014
Publisher
Packt
Pages
202
ISBN
9781783553631

 

Chapter 1. Interactive Input

Before we start creating our game, it is a good idea to figure out our controls. We'll create a script that will hold our inputs, and create control profiles for both the keyboard/mouse as well as the Xbox 360 Controller. Then, we'll add functionalities to be able to switch between the profiles and customize them as well. Control configurations like these are a key element to games, especially PC games.

In this chapter, we will cover the following topics:

  • Creating controls for the Xbox 360 Controller

  • Creating controls for a keyboard

  • Writing a function to detect whether our controller device is plugged in

  • Customizing our controls

  • Letting players switch controls

  • Switching controls with Graphical User Interface (GUI) buttons

  • Resetting controls back to factory settings

 

Picking the controls


Before we start creating our game, we should decide how the player will play the game. The controls are one of the most key parts of a game.

Mapping the needed controls

For the game that we will create, we will need several controls. Some are already included in the input manager within Unity, while some are not. The following table shows what default controls we will be using, and what buttons we'll use for them:

Action

Keyboard/mouse

Xbox 360 Controller

Movement

WASD keys

Left thumbstick

Rotate camera

Mouse

Right thumbstick

Item bar buttons

1234 keys

Directional pad

Inventory

The I key

The A button

Pause game

The Esc key

The Start button

Attack / use an item

The left mouse button

The right trigger

Aim

The right mouse button

The left trigger

Checking the input manager

In the following screenshot, you can see that there are default inputs already implemented, which we can use for the movement, rotate camera, attack/use item, and aim actions:

As you can see, we still need to add inputs for the inventory, pause game, and item bar buttons. We will also need to make sure that the inputs we enter will support inputs from the Xbox 360 Controller.

Checking the Xbox 360 Controller inputs

Before we add stuff into the input manager, we should take a look at what the inputs are on the Xbox 360 Controller. This will help us integrate the controller inputs in the input manager, as well as give us an insight on how to code the controller inputs.

Adding additional controller inputs

To get started, access your input manager by navigating to the Edit menu, hovering over Project Settings, and clicking on Input. Open up the Axes dropdown by clicking on the arrow next to it and change the number in the Size parameter to be a value higher. This will add another input at the bottom of the list, which we can use for one of our types of inputs.

By default, by creating a new type of input, the input manager duplicates the bottom input. So open it and we'll make our changes. Follow these steps to create our new input:

  1. Change the value of the Name parameter to A_360.

  2. Change the value of the Positive Button parameter to joystick button 0.

Adding a start button and trigger inputs

As you can see, it's fairly easy to add an Xbox 360 input in the input manager. You can follow the same steps to add the start button; just change the value of the Name parameter to Start_360 and the value of the positive button to joystick button 7. For the two triggers, you will need to follow slightly different steps:

  1. Change the value of the Name parameter to Triggers_360.

  2. Change the value of the Sensitivity parameter to 0.001.

  3. Check the Invert parameter.

  4. Change the value of the Type parameter to Joystick Axis.

  5. Change the value of the Axis parameter to 3rd Axis (Joysticks and Scrollwheel).

Adding directional pad inputs

For the directional pad, we'll need to make the horizontal buttons and vertical buttons separately, but these will both be similar to how we set up the triggers. First, we will create the horizontal directional pad input:

  1. Change the value of the Name parameter to HorizDpad_360.

  2. Change the value of the Sensitivity parameter to 1.

  3. Change the value of the Type parameter to Joystick Axis.

  4. Change the value of the Axis parameter to 6th Axis (Joysticks).

For the vertical directional pad input, you can follow the exact same steps as we did for the horizontal directional pad input; just change the value of Name to VertDpad_360 and change the value of Axis to 7th Axis (Joysticks). This completes the Xbox 360 Controller inputs; all that's left are the PC inputs.

Adding PC control inputs

Most of our PC control inputs are already integrated into the input manager; all that is left are the number keys, I key, and Esc key.

You can actually follow the same steps as at the beginning of this chapter, when we added the Xbox 360 buttons. For the number keys you'll want to change each of their names to num1, num2, num3, and num4. As for their positive button parameters, change their names to 1, 2, 3, and 4, accordingly.

The I key name will be I_Key and its positive button parameter will be i. For the Esc key, we will want the Name parameter to be Esc_Key and its positive button parameter will be escape.

 

Housing our control script


Now that we have our control inputs set up, we'll set up our script that will house all our control-based scripting.

Creating and naming the script

Create a new script either by right-clicking on Project Window, hovering over the Create tab, and clicking on the C# script, or by navigating through the Assets menu and creating the new C# script this way. Once you have done this, rename the script ControlConfig.

Formatting the script

After you have created and named the script, open it. Ensure that the class name, ControlConfig, is the same as the filename. You'll see that Unity has created the start and update functions for use already. You should delete both of these functions, which will leave you with an open and empty class.

 

Creating the device detector


The first function we'll create is one that will detect whether we actually have a gamepad plugged in. Unity inherently gives us a way to make this very easy.

Adding the variables needed

First, we'll add variables that we'll use in the detection and identification functions. Add these to the top of your script, just after the class declaration:

bool isControllerConnected = false;
public string Controller = "";

This Boolean will be used in later functions to determine whether there is a gamepad connected. The string will be used to hold the name of the gamepad connected.

Creating the detection function

Our next step is to add the DetectController function. This will use the Boolean we created earlier and check whether there is a gamepad connected. Add the following code to your script:

void DetectController()
{
  try
  {
    if(Input.GetJoystickNames()[0] != null)
    {
      isControllerConnected = true;
      IdentifyController();
    }
  }
  catch
  {
    isControllerConnected = false;
  }
}

This function uses the GetJoystickNames function of the input, which gets and returns an array of strings, which consists of the names of the connected gamepads. We use this to set our Boolean to true or false; true meaning there's a device connected and false meaning that the game couldn't detect a device. The reason we use a try-catch expression is because if there is no gamepad connected Input.GetJoystickNames() will give you an IndexOutOfRangeException error.

Creating the identifier function

Our last step in creating the device detector will be to add the ability to identify the gamepad connected. Add this function to the script, just below the DetectController function:

void IdentifyController()
{
  Controller = Input.GetJoystickNames()[0];
}

As you can see, we are assigning the name of the gamepad connected to our Controller variable. To use this function, call it within the DetectController function, in the if statement, where we set isControllerConnected to true.

 

Let's get set and show them


The next step in our Control script is to set up our controls to be able to customize what they do, and display what each control does.

Adding variables for each control

At the top of your script, after your other variables, add these new variables:

public string PC_Move, PC_Rotate, PC_Item1, PC_Item2, PC_Item3, PC_Item4, PC_Inv, PC_Pause, PC_AttackUse, PC_Aim;
public string Xbox_Move, Xbox_Rotate, Xbox_Item1, Xbox_Item2, Xbox_Item3, Xbox_Item4, Xbox_Inv, Xbox_Pause, Xbox_AttackUse, Xbox_Aim;

We will use these variables to display our controls on the screen. Later, we'll use them for customization as well. Add this code to assign the default values to our new variables:

void SetDefaultValues()
{
  if(!isControllerConnected)
  {
    PC_Move = "WASD";
    PC_Rotate = "Mouse";
    PC_Item1 = "1";
    PC_Item2 = "2";
    PC_Item3 = "3";
    PC_Item4 = "4";
    PC_Inv = "I";
    PC_Pause = "Escape";
    PC_AttackUse = "Left Mouse Button";
    PC_Aim = "Right Mouse Button";
  }
  else
  {
    PC_Move = "WASD";
    PC_Rotate = "Mouse";
    PC_Item1 = "1";
    PC_Item2 = "2";
    PC_Item3 = "3";
    PC_Item4 = "4";
    PC_Inv = "I";
    PC_Pause = "Escape";
    PC_AttackUse = "Left Mouse Button";
    PC_Aim = "Right Mouse Button";
    Xbox_Move = "Left Thumbstick";
    Xbox_Rotate = "Right Thumbstick";
    Xbox_Item1 = "D-Pad Up";
    Xbox_Item2 = "D-Pad Down";
    Xbox_Item3 = "D-Pad Left";
    Xbox_Item4 = "D-Pad Right";
    Xbox_Inv = "A Button";
    Xbox_Pause = "Start Button";
    Xbox_AttackUse = "Right Trigger";
    Xbox_Aim = "Left Trigger";
  }
}

We will set these variables in a function because later we will use this function again to reset the controls if they are customized. The function uses our isControllerConnected variable to determine whether a gamepad is plugged in or not, and then assigns the appropriate data.

Adding a function to display the variables

Next, we will use the OnGUI function to display our controls onto the screen. We will create a menu that will show each action and their controls for a PC and Xbox 360 Controller, very similar to the table shown at the beginning of this chapter. Add this code to the bottom of your script:

void OnGUI()
{
  GUI.BeginGroup(new Rect(Screen.width/2 - 300, Screen.height / 2 - 300, 600, 400));
  GUI.Box(new Rect(0,0,600,400), "Controls");
  GUI.Label(new Rect(205, 40, 20, 20), "PC");
  GUI.Label(new Rect(340, 40, 125, 20), "Xbox 360 Controller");

  GUI.Label(new Rect(25, 75, 125, 20), "Movement: ");
  GUI.Button(new Rect(150, 75, 135, 20), PC_Move);
  GUI.Button(new Rect(325, 75, 135, 20), Xbox_Move);

  GUI.Label(new Rect(25, 100, 125, 20), "Rotation: ");
  GUI.Button(new Rect(150, 100, 135, 20), PC_Rotate);
  GUI.Button(new Rect(325, 100, 135, 20), Xbox_Rotate);

  GUI.Label(new Rect(25, 125, 125, 20), "Item 1: ");
  GUI.Button(new Rect(150, 125, 135, 20), PC_Item1);
  GUI.Button(new Rect(325, 125, 135, 20), Xbox_Item1);

  GUI.Label(new Rect(25, 150, 125, 20), "Item 2: ");
  GUI.Button(new Rect(150, 150, 135, 20), PC_Item2);
  GUI.Button(new Rect(325, 150, 135, 20), Xbox_Item2);

  GUI.Label(new Rect(25, 175, 125, 20), "Item 3: ");
  GUI.Button(new Rect(150, 175, 135, 20), PC_Item3);
  GUI.Button(new Rect(325, 175, 135, 20), Xbox_Item3);

  GUI.Label(new Rect(25, 200, 125, 20), "Item 4: ");
  GUI.Button(new Rect(150, 200, 135, 20), PC_Item4);
  GUI.Button(new Rect(325, 200, 135, 20), Xbox_Item4);

  GUI.Label(new Rect(25, 225, 125, 20), "Inventory: ");
  GUI.Button(new Rect(150, 225, 135, 20), PC_Inv);
  GUI.Button(new Rect(325, 225, 135, 20), Xbox_Inv);

  GUI.Label(new Rect(25, 250, 125, 20), "Pause Game: ");
  GUI.Button(new Rect(150, 250, 135, 20), PC_Pause);
  GUI.Button(new Rect(325, 250, 135, 20), Xbox_Pause);

  GUI.Label(new Rect(25, 275, 125, 20), "Attack/Use: ");
  GUI.Button(new Rect(150, 275, 135, 20), PC_AttackUse);
  GUI.Button(new Rect(325, 275, 135, 20), Xbox_AttackUse);

  GUI.Label(new Rect(25, 300, 125, 20), "Aim: ");
  GUI.Button(new Rect(150, 300, 135, 20), PC_Aim);
  GUI.Button(new Rect(325, 300, 135, 20), Xbox_Aim);
  GUI.EndGroup();
}

The preceding code is fairly self-explanatory; we use GUI labels to show what actions the player can do, then use the GUI buttons to show what inputs the actions are mapped to. Later, we'll use these buttons as a way to customize our controls.

 

Let's switch!


Now, we'll create a way for the player to switch between PC and Xbox 360 Controller controls.

Creating control profiles

To create our profiles, we'll need to add a new variable. Add the following enum to the top of our script, before the class declaration:

public enum ControlProfile { PC, Controller };

Add it to your variables as well, like this:

public ControlProfile cProfile;

Finally, go to the DetectController() function. Add this line of code before the line of code where you call the IdentifyController() function in the if statement:

cProfile = ControlProfile.Controller;

After this, add an else statement to the if statement with another line of code after it:

else
  cProfile = ControlProfile.PC;

We are setting our enum variable in the DetectController() function to give us a default control profile. This is a fast and effective way to give our player the best control profile possible.

Adding a profile switching function

Next, we'll add a function that we can call to manually switch the control profile. Add this function to our code:

void SwitchProfile (ControlProfile Switcher)
{
  cProfile = Switcher;
}

We can call this function later to let the player choose between using the keyboard/mouse or the Xbox 360 Controller.

Adding the GUI interaction function

Now, we'll add a button to the bottom right of our controls page to let the player pick between the keyboard/mouse and Xbox 360 Controller. Add this code to your onGUI() function, just before the line where we end the group:

GUI.Label(new Rect(450, 345, 125, 20), "Current Controls");
if(GUI.Button(new Rect(425, 370, 135, 20), cProfile.ToString()))
{
  if(cProfile == ControlProfile.Controller)
    SwitchProfile(ControlProfile.PC);
  else
    SwitchProfile(ControlProfile.Controller);
}

The text on the button will display which current control profile is being used. When the player clicks on the button, it will switch the control profile.

 

Customization is key


It's time to customize our controls! We'll go over a couple of ways to add customization to our controls. Unity doesn't allow us to edit the input properties while in-game, so we will create a couple of ways to change the controls ourselves. In our game, we will utilize both these ways.

Swapping control schemes

Our first method will be to switch between preset control schemes. To start off, we'll add a bunch of variables that we will use for our controls:

string ControlScheme;
public KeyCode pcItem1, pcItem2, pcItem3, pcItem4, pcInv, pcPause, pcAttackUse, pcAim, xInv, xPause;

Since we can't modify the input properties, some of our controls will not be customized, such as movement, camera rotation, Xbox 360 Controller attack/use, and Xbox 360 Controller item switching. Next, we will need to set some default values to these variables; we'll modify our SetDefaultValues() function to look like this:

void SetDefaultValues()
{
  ControlScheme = "Scheme A";
  if(!isControllerConnected)
  {
    PC_Move = "WASD";
    PC_Rotate = "Mouse";
    PC_Item1 = "1";
    PC_Item2 = "2";
    PC_Item3 = "3";
    PC_Item4 = "4";
    PC_Inv = "I";
    PC_Pause = "Escape";
    PC_AttackUse = "Left Mouse Button";
    PC_Aim = "Right Mouse Button";

    pcItem1 = KeyCode.Alpha1;
    pcItem2 = KeyCode.Alpha2;
    pcItem3 = KeyCode.Alpha3;
    pcItem4 = KeyCode.Alpha4;
    pcInv = KeyCode.I;
    pcPause = KeyCode.Escape;
    pcAttackUse = KeyCode.Mouse0;
    pcAim = KeyCode.Mouse1;
  }
  else
  {
    PC_Move = "WASD";
    PC_Rotate = "Mouse";
    PC_Item1 = "1";
    PC_Item2 = "2";
    PC_Item3 = "3";
    PC_Item4 = "4";
    PC_Inv = "I";
    PC_Pause = "Escape";
    PC_AttackUse = "Left Mouse Button";
    PC_Aim = "Right Mouse Button";
    Xbox_Move = "Left Thumbstick";
    Xbox_Rotate = "Right Thumbstick";
    Xbox_Item1 = "D-Pad Up";
    Xbox_Item2 = "D-Pad Down";
    Xbox_Item3 = "D-Pad Left";
    Xbox_Item4 = "D-Pad Right";
    Xbox_Inv = "A Button";
    Xbox_Pause = "Start Button";
    Xbox_AttackUse = "Right Trigger";
    Xbox_Aim = "Left Trigger";

    pcItem1 = KeyCode.Alpha1;
    
	pcItem2 = KeyCode.Alpha2;
    pcItem3 = KeyCode.Alpha3;
    pcItem4 = KeyCode.Alpha4;
    pcInv = KeyCode.I;
    pcPause = KeyCode.Escape;
    pcAttackUse = KeyCode.Mouse0;
    pcAim = KeyCode.Mouse1;
    xInv = KeyCode.I;
    xPause = KeyCode.Escape;
    }
  }

Next, we will add a function to our script that will allow the player to switch between control schemes:

void SwitchControlScheme(string Scheme)
{
  switch(Scheme)
  {
  case "Scheme A":
    SetDefaultValues();
  break;
  case "Scheme B":
    if(!isControllerConnected)
    {
      PC_Move = "WASD";
      PC_Rotate = "Mouse";
      PC_Item1 = "Numpad 1";
      PC_Item2 = "Numpad 2";
      PC_Item3 = "Numpad 3";
      PC_Item4 = "Numpad 4";
      PC_Inv = "Numpad +";
      PC_Pause = "Enter";
      PC_AttackUse = "Right Mouse Button";
      PC_Aim = "Left Mouse Button";
        
      pcItem1 = KeyCode.Keypad1;
      pcItem2 = KeyCode.Keypad2;
      pcItem3 = KeyCode.Keypad3;
      pcItem4 = KeyCode.Keypad4;
      pcInv = KeyCode.KeypadPlus;
      pcPause = KeyCode.Return;
      pcAttackUse = KeyCode.Mouse1;
      pcAim = KeyCode.Mouse0;
    }
    else
    {
      PC_Move = "WASD";
      PC_Rotate = "Mouse";
      PC_Item1 = "Numpad 1";
      PC_Item2 = "Numpad 2";
      PC_Item3 = "Numpad 3";
      PC_Item4 = "Numpad 4";
      PC_Inv = "Numpad +";
      PC_Pause = "Enter";
      PC_AttackUse = "Right Mouse Button";
      PC_Aim = "Left Mouse Button";
      Xbox_Move = "Left Thumbstick";
      Xbox_Rotate = "Right Thumbstick";
      Xbox_Item1 = "D-Pad Up";
      Xbox_Item2 = "D-Pad Down";
      Xbox_Item3 = "D-Pad Left";
      Xbox_Item4 = "D-Pad Right";
      Xbox_Inv = "B Button";
      Xbox_Pause = "Back Button";
      Xbox_AttackUse = "Right Trigger";
      Xbox_Aim = "Left Trigger";
        
      pcItem1 = KeyCode.Keypad1;
      pcItem2 = KeyCode.Keypad2;
      pcItem3 = KeyCode.Keypad3;
      pcItem4 = KeyCode.Keypad4;
      pcInv = KeyCode.KeypadPlus;
      pcPause = KeyCode.Return;
      pcAttackUse = KeyCode.Mouse1;
      pcAim = KeyCode.Mouse0;
      xInv = KeyCode.JoystickButton1;
      xPause = KeyCode.JoystickButton6;
    }
  break;
  }
}

As you can see, this function is very similar to our SetDefaultValues() function; it acts the same way. SwitchControlScheme() takes a string that determines which control scheme to use and then assigns the appropriate data. The first scheme is the default control scheme, while the other one is a new scheme. The new scheme changes the following:

  • Item keys are now on the keypad

  • Inventory buttons are now the + key and B key

  • Attack/use inputs are switched on the mouse

  • Pause has been changed to the Enter key and the Backspace key

Adding a control switch button to the GUI

Lastly, we'll need to add a GUI button to our OnGUI function to allow the player to switch control schemes. Add the following before the line that ends the group:

GUI.Label(new Rect(15, 345, 125, 20), "Current Control Scheme");
if(GUI.Button(new Rect(25, 370, 135, 20), ControlScheme))
{
  if(ControlScheme == "Scheme A")
  {
    SwitchControlScheme("B");
    ControlScheme = "Scheme B";
  }
  else
  {
    SwitchControlScheme("A");
    ControlScheme = "Scheme A";
  }
}

This button, when clicked, will call the SwitchControlScheme() function and pass it a letter determining the control scheme being used.

Cycling control inputs

Our next method of customization will let the player click on one of the GUI buttons in our controls, and pick another control to switch it. To start off, we'll add variables that we'll use to hold the original values of our controls. The last two variables will be used to allow us to customize our controls:

private KeyCode orig_pcItem1, orig_pcItem2, orig_pcItem3, orig_pcItem4, orig_pcInv, orig_pcPause, orig_xInv, orig_xPause;
bool ShowPopup = false;
KeyCode PreviousKey;

In the SetDefaultValues function, assign these variables to our previous control variables in both the if and else statements:

orig_pcItem1 = pcItem1;
orig_pcItem2 = pcItem2;
orig_pcItem3 = pcItem3;
orig_pcItem4 = pcItem4;
orig_pcInv = pcInv;
orig_pcPause = pcPause;

Assign the Xbox 360 Controller controls in the else statement:

orig_xInv = xInv;
orig_xPause = xPause;

Next, we are going to add a function that we'll call to switch our keys:

void SetNewKey(KeyCode KeyToSet, KeyCode SetTo)
{
  switch(KeyToSet)
  {
  case KeyCode.Alpha1:
    pcItem1 = SetTo;
    PC_Item1 = SetString(pcItem1.ToString());
    break;
  case KeyCode.Alpha2:
    pcItem2 = SetTo;
    PC_Item2 = SetString(pcItem2.ToString());
    break;
  case KeyCode.Alpha3:
    pcItem3 = SetTo;
    PC_Item3 = SetString(pcItem3.ToString());
    break;
  case KeyCode.Alpha4:
    pcItem4 = SetTo;
    PC_Item4 = SetString(pcItem4.ToString());
    break;
  case KeyCode.I:
    pcInv = SetTo;
    PC_Inv = SetString(pcInv.ToString());
    break;
  case KeyCode.Escape:
    pcPause = SetTo;
    PC_Pause = SetString(pcPause.ToString());
    break;
  case KeyCode.JoystickButton1:
    xInv = SetTo;
    Xbox_Inv = SetString(xInv.ToString());
    break;
  case KeyCode.JoystickButton6:
    xPause = SetTo;
    Xbox_Pause = SetString(xPause.ToString());
    break;
  }
}

This new function takes in two properties: the first one will be what KeyCode we set and the second one will be what KeyCode we are setting the key to. You can see that we also set our string variables, which are used in the GUI with another function. We'll create that function now:

string SetString(string SetTo)
{
  switch(SetTo)
  {
  case "Alpha1":
    SetTo = "1";
    break;
  case "Alpha2":
    SetTo = "2";
    break;
  case "Alpha3":
    SetTo = "3";
    break;
  case "Alpha4":
    SetTo = "4";
    break;
  case "Return":
    SetTo = "Enter";
    break;
  case "Escape":
    SetTo = "Escape";
    break;
  case "I":
    SetTo = "I";
    break;
  case "JoystickButton6":
    SetTo = "Start Button";
    break;
  case "JoystickButton1":
    SetTo = "A Button";
    break;
  }
  return SetTo;
}

Now in our OnGUI function, we'll need to adjust some of our code. Before we start our controls group, we will check whether our controls pop up is activated. Add the if statement to our code and encapsulate the Controls Group:

if(!ShowPopup)
{

Next, we'll edit some of our GUI buttons to allow customization. Start with the PC_Item1 button and change it to this code:

if(GUI.Button(new Rect(150, 125, 135, 20), PC_Item1))
{
  ShowPopup = true;
  PreviousKey = pcItem1;
}

Do the same thing for the following buttons:

  • PC_Item2

  • PC_Item3

  • PC_Item4

  • PC_Pause

  • PC_Inv

  • Xbox_Inv

  • Xbox_Pause

Set ShowPopup to true and PreviousKey to its expected value, accordingly, such as pcItem2, pcItem3, pcItem4, and so on. Place a closing bracket afterwards to close the if statement that we created earlier.

Adding the controls pop up to the GUI

It's time to add our controls pop up to the GUI. This is where the player will select what control to swap. To do this, we will add an else statement, extending our if statement, to create the pop up:

else
{
  GUI.BeginGroup(new Rect(Screen.width/2 - 300, Screen.height / 2 - 300, 600, 400));
  GUI.Box(new Rect(0,0,600,400), "Pick A Control to Switch");
  if(GUI.Button(new Rect(150, 125, 135, 20), "1"))
  {
    SetNewKey(PreviousKey, orig_pcItem1);
    ShowPopup = false;
  }
  if(GUI.Button(new Rect(150, 150, 135, 20), "2"))
  {
    SetNewKey(PreviousKey, orig_pcItem2);
    ShowPopup = false;
  }
  if(GUI.Button(new Rect(150, 175, 135, 20), "3"))
  {
    SetNewKey(PreviousKey, orig_pcItem3);
    ShowPopup = false;
  }
  if(GUI.Button(new Rect(150, 200, 135, 20), "4"))
  {
    SetNewKey(PreviousKey, orig_pcItem4);
    ShowPopup = false;
  }
  if(GUI.Button(new Rect(150, 225, 135, 20), "I"))
  {
    SetNewKey(PreviousKey, orig_pcInv);
    ShowPopup = false;
  }
  if(GUI.Button(new Rect(150, 250, 135, 20), "Escape"))
  {
    SetNewKey(PreviousKey, orig_pcPause);
    ShowPopup = false;
  }
  if(GUI.Button(new Rect(325, 225, 135, 20), "A Button"))
  {
    SetNewKey(PreviousKey, orig_xInv);
    ShowPopup = false;
  }
  if(GUI.Button(new Rect(325, 250, 135, 20), "Start Button"))
  {
    SetNewKey(PreviousKey, orig_xPause);
    ShowPopup = false;
  }
  GUI.EndGroup();
}

When the player clicks on one of these new buttons, the SetNewKey function is called. When called, we pass PreviousKey, which is the key the player is customizing, as well as the key they select, which is the new value of PreviousKey. This is a great and simple way to change controls, which makes it simple for the player.

Resetting the controls

In this section, we will add the ability to allow the player to reset the controls to their default values.

Adding the Reset function

The reset function will use our SetDefaultValues() function as well as reset a couple of our other variables:

void Reset()
{
  SetDefaultValues();
  ShowPopup = false;
  PreviousKey = KeyCode.None;
}

Here, we call our SetDefaultValues() function, and then reset some other variables. Resetting the ShowPopup Boolean and our PreviousKey KeyCode will ensure that everything related to customization of controls has been reset.

Adding the Reset input

Now, we'll make a GUI button that will call the Reset function. Add this just before the line of code that ends the GUI group in the OnGUI() function's if statement:

if(GUI.Button(new Rect(230, 370, 135, 20), "Reset Controls"))
{
  Reset();
}

When the player clicks on this button, the controls will be set to their default values. Here is the finished product of the script that you just created:

 

Playtesting


Now for the most important part, playtesting! Go ahead and play with the GUI buttons and make sure everything works as it is supposed to. Add the Debug.Log statements to where you think you may have problems and see which variable is set to what. Plug in your Xbox 360 Controller and make sure that it detects your controller.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

 

Summary


In this chapter, you learned a great deal about how to create and handle control schemes. You also learned how to change preset control schemes, as well as swap the controls. You can now create a game that will support both the keyboard/mouse and Xbox 360 Controller. This is something that is pivotal to games and game design; not everyone likes to use non-customizable controls.

In the next chapter, we'll go over how to utilize the GUI more in depth. You will learn about how to create 3D GUI elements as well as 2D elements. Later on in this book, we will use these new GUI elements to create a more engaging experience.

About the Author
  • Kyle D'Aoust

    Kyle D'Aoust has been programming for about 10 years. In 2004, at the age of 14, he taught himself the C++ language. By the end of high school, he had learned Visual Basic and JavaScript as well. In college, he majored in game production and specialized in the Unity engine using C#. After graduating from college, Kyle started his career with gamifying software. He is currently working as a Serious Games Developer at Quicken Loans, creating games used as training material.

    Browse publications by this author
Unity Game Development Scripting
Unlock this book and the full library FREE for 7 days
Start now