Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

var as Input

Discussion in 'Scripting' started by Giovane, Oct 11, 2019.

  1. Giovane

    Giovane

    Joined:
    Sep 23, 2019
    Posts:
    36
    is there a way of using var as input, so if you have multiple players you could use only one script and change the input buttons in the inspector?
     
  2. TheHammer1

    TheHammer1

    Joined:
    Oct 15, 2015
    Posts:
    25
    What do you mean by "Input"? Are you referring to the class?
     
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,835
    Not entirely sure what you mean by "var" in this context.

    If you're using Unity's keyboard input functions like GetButton and GetAxis and you're trying to make it so that different instances of a script will read different inputs, you can use string-type variables to represent the inputs you should check. (But beware of spelling errors.)

    if (Input.GetButtonDown(myStringVar))


    You could even build the input names programmatically if they're somehow derived from the player number. For instance, if you had inputs with names like "player0fire", "player1fire", "player0jump", "player1jump", etc. then you could get input with something like

    if (Input.GetButtonDown("player" + playerNum + "fire"))


    or, perhaps a little more neatly,

    if (Input.GetButtonDown(string.Format("player{0}fire", playerNum)))


    But Unity's Input class doesn't have a built-in concept of "players", so that only works as long as you manually set up all of your input names to fit the pattern.

    There are plugins on the asset store you can get that will assist with certain kinds of input processing if you want; I've recently been using Rewired.
     
  4. Giovane

    Giovane

    Joined:
    Sep 23, 2019
    Posts:
    36
    This is working very well, I will change all the code, so player 2 have the same code but the input keys will be the arrows instead of wasd