Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Unity Game Development Scripting
Unity Game Development Scripting

Unity Game Development Scripting: Write efficient C# scripts to create modular key game elements that are usable for any kind of Unity project

eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Unity Game Development Scripting

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:

Checking the input manager

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.

Checking the Xbox 360 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:

Adding the Reset input

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.

Left arrow icon Right arrow icon

Description

The intuitive and powerful Unity game engine is one of the most widely used and best loved packages for game development. Unity scripting is an essential but challenging skill to master in order to create custom game elements. Learning modular scripting allows you to rewrite as little code as possible as you deploy your scripts to multiple projects and work easier, quicker, and more efficiently than before. In each chapter of this book, you'll learn how to script new game elements. Beginning with making custom controls for the keyboard and mouse, as well as the Xbox 360 Controller, you'll then get to grips with more complex systems such as inventory, data saving, and artificial intelligence. As you create these elements, you'll also learn how to make your scripts simpler and easy to use. This will allow drag-and-drop deployment, which is to be used by designers and nonprogrammers. Finally, you'll combine all of your newfound skills to create your own complete game project.
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 22, 2014
Length: 202 pages
Edition : 1st
Language : English
ISBN-13 : 9781783553631
Vendor :
Unity Technologies
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Dec 22, 2014
Length: 202 pages
Edition : 1st
Language : English
ISBN-13 : 9781783553631
Vendor :
Unity Technologies
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 97.98
Unity Game Development Scripting
$48.99
Unity Game Development Blueprints
$48.99
Total $ 97.98 Stars icon
Banner background image

Table of Contents

11 Chapters
1. Interactive Input Chevron down icon Chevron up icon
2. GUI Time Chevron down icon Chevron up icon
3. Expandable Item Classes Chevron down icon Chevron up icon
4. Inventory Chevron down icon Chevron up icon
5. Enemy and Friendly AIs Chevron down icon Chevron up icon
6. Keeping Score Chevron down icon Chevron up icon
7. Creating Save and Load Systems Chevron down icon Chevron up icon
8. Aural Integration Chevron down icon Chevron up icon
9. Game Settings Chevron down icon Chevron up icon
10. Putting It All Together Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(7 Ratings)
5 star 42.9%
4 star 28.6%
3 star 28.6%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




MR B BYFORD Feb 16, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Hugely useful overview of various game design has its and how they can work in unity.Got this after the 2d game development in unity book, and was please at how it built on my knowledge and didn't spell things that I already knew. Not for absolute beginners.
Amazon Verified review Amazon
Mário Freitas Mar 01, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is written in very concise and simple to understand way, guiding the reader the whole way to actually create a simple working game, and covering most topics on game development scripting.I would highly recommend this book to people who are new to Unity scripting and to those who would like to learn more about how to structurally and conceptually organize a game from the point of view of game development scripting.The book also offers standard approaches to the implementation of features that are present and required in any game.
Amazon Verified review Amazon
Peter Matthew Apr 30, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As a Lecturer in Games Development I am always on the lookout for books that can help my students improve their understanding of both c# and Unity3d. This book provides a lot of very good tutorials and explanations that cover a variety of subjects within the games development area. The sections are clearly written and provides good examples of the code being discussed. After discussing the book with some of my second year students they described it as “very helpful” and “easier to understand than a lot of other books”.Some criticisms of the book are that the sections are a little abstract in places jumping from topic to topic and it relies on a previous understanding of coding knowledge to get the most out of it, therefore lending itself more to an intermediate or advanced user.Regardless the author does an excellent job of explaining useful scripts that most games developers will want to include: such as re -bindable controller settings and user interface development, therefore providing the reader with a practical set of scripting examples.I would recommend this book for anyone wanting to improve their understanding of Unity scripting and my department is now using this book as part of our essential reading list for all second year games programmers.
Amazon Verified review Amazon
Robert L. Dixon Feb 07, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I read a lot of books about Unity and C# since I'm always trying to up my game, so to speak. This book has some good sections but overall doesn't cohere as well as it could. But it could be useful for people with some Unity experience who are looking for specific techniques.It jumps right into scripting individual subsystems without talking about what kind of game is going to be built and how everything will fit together. Later on you learn the example game is an RPG-style game with characters, weapons and objects. It would have been nice to know this ahead of time, because some of the chapters are only relevant to this type of game.Overall this is more like a "cookbook" of various recipes, as opposed to a step-by-step guide to building a real game. If you already have some experience coding C# in Unity, and you are interested in some of the chapter topics, you should find the book useful.Here's a brief rundown on some specific chapters:* The first chapter on Interactive Input present a nice technique for switching among input control schemes. However there's an emphasis on supporting the XBox 360 controller which might not be relevant to a lot of developers.* The GUI chapter relies a little too heavily on the old, mostly obsolete Unity GUI approach, so it is not too useful in the post-Unity-4.6 world.* The Expandable Item Classes chapter presents a nice starting point for structuring in-game items that affect player characters and objects.* The chapter on AI covers two different AI topics: simple enemy decision-making (switching an enemy object among Idle, Guard, Combat, Flee states), and pathfinding. The pathfinding section gives a good introduction to Unity's NavMesh system, which is not covered in many other books. The example for this chapter uses the AI scripts to animate some freely-available skeleton models (from the Asset Store) around an environment.* The chapter about Keeping Score on the other hand presents some real brute-force coding with hard-coded achievement thresholds and such. There are better and simpler ways to code this, so I would give this chapter a pass.* The same could be said for the next chapter, which covers Saving and Loading Data. It uses XML, which is generally heavier and harder to work with than JSON, and again shows some brute-force coding that might not hold up well over time.* Chapter 8 deals with audio and offers some simple, reusable classes for managing and playing sounds.* The final chapter, "Putting It All Together," builds a simple game by assembling all the subsystems from previous chapters. It's very nice to see all the parts working together at the end. This chapter could have been fleshed out a bit more. It would have been nice to have an overview, like a diagram, of how all the subsystems fit together, rather than a step-by-step "now add this, now add this" sequence. In fact this kind of overview would have been really useful prior to Chapter 1, so the reader can go into the rest of the book knowing what to expect.Overall there are a lot of things to learn from this book. In addition there is a nice emphasis on play-testing at the end of each chapter, with suggestions of ways to enhance the examples in your own games. But it's not a complete guide to building your own games in Unity.
Amazon Verified review Amazon
Matthew Feb 09, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Bottom line up front, this book is a great tool to keep in your kit bag. With a basic knowledge of programming and Unity, I started an indie game development company with several game ideas in mind. What I quickly discovered was, like most things in life, there are multiple ways to accomplish a single task within Unity. This created a challenge I hadn’t planned for. Originally I thought it would be difficult to find the right literature to help me achieve my goal, but instead I found that I was inundated with information. I recently came across “Unity Game Development Scripting” by Kyle D'Aoust and became quite pleased with what I had found. The book is laid out in a very efficient manner covering all the major aspects of creating a game. The first chapter deals with the most important aspect, defining user input. It lays out two options one for keyboards and the other for an Xbox controller. At first glance the reader may be tempted to think this doesn’t apply to me because I’m not developing for those platforms. This may be true, but if the reader looks deeper they will start to see how the techniques used in the book can transfer into other projects. The process the writer took to define different aspects and requirements for control are useful when designing the controls for all games. Chapters 5 and 7 are also great examples of a situation where the techniques used are beneficial to any reader attempting to develop a game in Unity. I have personally struggled with scripting enemy artificial intelligence in a 2D platformer game and have waffled between different techniques. After reading chapter 5, I was able to add a more efficient solution to my games even though the writer is referencing 3D game creation. In addition, chapter 7 answers the question of saving game progress. When I first started developing games this task perplexed me, but “Unity Game Development Scripting” by Kyle D'Aoust does an excellent job of defining C# scripting that accomplishes the task. Though I was overall happy with this book, there was one point of contention I had with the way it was written. The author provides numerous coding examples written in C# throughout each chapter. He does a good job giving a description after each block of coding, but I found it to be rather taxing on the mind to connect the explanations with the code previously read. A better way to accomplish this would have been to add comments directly into the code itself. This would have personally helped me better follow the readings. Again, this book is an excellent tool for any developer to have. If you don’t have an intermediate understanding of programming and Unity, you will probably find this book to be frustrating as it is not a tutorial based piece of work. But if you are looking for a resource to help refine and/or add to your own techniques for game development then this is the right place to start.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela