- Home /
How to create a game with two gamepads?
I want to create a co-op game with two gamepads, one for each player. how do I specify each gamepad in script? This is my main question, as I can't find documentation, and if there is a way it is probably not too different from one gamepad.
My second sub-question regarding this is, how do I do split screens?
Thank you.
The documentation you're looking for is at : http://docs.unity3d.com/$$anonymous$$anual/ConventionalGameInput.html
Answer by Cherno · Jun 13, 2015 at 04:50 PM
Open the input manager, you can create inputs for multiple gamepads there (Edit->Project Settings->Input). You basically have to set up all buttons and axes to register input from controller 1,2 etc. with the "Joy num" field. I have uploaded my Input Manager settings which has complete input settigns for four gamepads. Make sure to create a copy of you own file should you decide to use it. InputManager.asset The file goes into the ProjectSettigns folder inside your project folder. Note that each input name starts with "Px" where x is a number from 1 to 4, corresponding to the player number. This helps you use the same input script for all players, as you can just add "P" and the player number (which you could store as an int value) to the beginning of the input string.
public int playerNumber = 1;
private string buttonstring_2;
void Start() {
buttonstring_2 = "P" + playerNumber + "Button" + 2;
}
void Update() {
if (Input.GetButtonDown(cInput.buttons[2])) {
Debug.Log("Button 2 pressed for player " + playerNumber);
}
}
Personally, I made a custom cclass that holds all input strings for axes and buttons for a player control script and assign it at the start of the game.
[System.Serializable]
public class CustomInput {
public string vertical_Left;
public string horizontal_Left;
public string vertical_Right;
public string horizontal_Right;
public string[] buttons;
}
public CustomInput cInput;
public int playerNumber = 1;
void Start() {
AssignControls(ref cInput, playerNumber);
}
public void AssignControls(ref CustomInput cInput, int pn) {
string s = "P" + pn;
cInput = new CustomInput();
cInput.horizontal_Left = s + "HorizontalLeft";
cInput.vertical_Left = s + "VerticalLeft";
cInput.horizontal_Right = s + "HorizontalRight";
cInput.vertical_Right = s + "VerticalRight";
cInput.buttons = new string[12];
for(int i = 0; i < cInput.buttons.Length; i++) {
cInput.buttons[i] = s + "Button" + i;
}
}
void Update() {
if (Input.GetButtonDown(cInput.buttons[2])) {
Debug.Log(cInput.buttons[2]);
}
}
As for splitting the screen: You need two cameras. In the inspector, the Camera component has a section "Viewport Rect", with four values. These control where the camera viewport rectangle is and it's size.