Reputation: 143
I'm trying to learn new Unity input system. In previous Unity input system,
if (Input.GetKeyDown("f"))
//do something when key 'f' is pressed
if (Input.GetKeyDown("g"))
//do something when key 'g' is pressed
if (Input.GetKeyDown("h"))
//do something when key 'h' is pressed
if (Input.GetKeyDown("j"))
//do something when key 'j' is pressed
would do any defined actions along keypress of f,g,h,j.
In new Unity input system, there is InputAction, which I can define Action Maps, Actions, and Properties. I can then implement functions as below, that can be called from PlayerInput under inspector of player object.
public void OnKey_F(InputAction.CallbackContext context)
{
if (context.started)
Debug.Log("Pressed F");
}
public void OnKey_G(InputAction.CallbackContext context)
{
if (context.started)
Debug.Log("Pressed G");
}
public void OnKey_H(InputAction.CallbackContext context)
{
if (context.started)
Debug.Log("Pressed H");
}
public void OnKey_J(InputAction.CallbackContext context)
{
if (context.started)
Debug.Log("Pressed J");
}
Is this right way to do the same funtion as above, under new Unity input system? The tutorials I found were mostly for WASD movement, which I already figured out how it works(2d vector). However, I'm not sure for this case which requires multiple keys for multiple functions.
Upvotes: 4
Views: 7029
Reputation: 39
There are a few ways to accomplish this, so I'm sorry I'm still not 100% on this form, but I thought I would share the simple implementation that has been working for me fine with multiple key presses, that bypasses most of the inspector work completely.
It starts with selecting the Player Input Map asset and confirming the "generate C# class" button is activated and apply.
Then in a MonoBehavior script, we instantiate that class, and add inline callback functions:
PlayerInputClass Inputs;
void Awake(){
Inputs = new PlayerInputClass();
Inputs.Enable();
// Examples. You can add as many as you want.
// You can put the ContextCallback to use
Inputs.Player.Move.performed += ctx => Movement = ctx.ReadValue<Vector2>();
// You can complete ignore it
Inputs.Player.Roll.performed += ctx => _RollInputFlag = true;
// You can define a function to handle the press
Inputs.Player.OtherAction.performed += FunctionThatRuns();
}
I typically opt to flip a flag so the script can decide exactly when to respond and revert the flag.
Note that here Player
is the action map name, and the names after are the actual action names. This is also nice because Intellisense will kick in and help.
Upvotes: 3