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

Input in multiple scripts

Discussion in 'Scripting' started by Snoober, Apr 5, 2020.

  1. Snoober

    Snoober

    Joined:
    Feb 11, 2020
    Posts:
    5
    Is it bad practice to poll for the same input in different scripts? So if I need to know if mouse1 is being clicked in two scripts? Is the best practice to make one class for the input and reference that in other scripts?
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,151
    I don't know about best practice, but if I needed to check for input, I'd probably have a single class handling it and calling stuff on the other scripts.
     
    Joe-Censored and Snoober like this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    Adding to the goodness from @Brathnann above, you want to identify points where value and meaning is added to the player's input, and centralize those points.

    For instance, "Pressing ESCAPE" means nothing in a vacuum.

    But in your game "Press ESCAPE" might mean many things: while playing it might mean pause, or cancel, or in the menus it might mean "back up one"

    Same thing goes for "FIRE" or "JUMP" or whatever.

    For your own sanity, it helps to gather all the input in one place in your program and store that input into variables of your own description in there, variables that make sense based on the state of your program at that moment.

    Or even better, have a separate "input for playing" script that is only active when playing, and an "input for menus" script that is only active when in menus.

    This way in the future if you decide you want to support touchscreen, or joystick, or any other crazy input device, you only have to change the mapping in that one (or few) module, and all the rest of your code Just Works(tm).
     
    Snoober and Brathnann like this.
  4. Snoober

    Snoober

    Joined:
    Feb 11, 2020
    Posts:
    5
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Unity's input system can handle checking for inputs, even the same inputs, in multiple scripts on the same frame just fine. The issue usually comes down to one of your own sanity once you have input checking spread across half your scripts.
     
    Snoober likes this.