#🖱️┃input-system
1 messages · Page 22 of 1
I have some code that depends on being able to get InputUser.all[0] so that it can check your current control scheme. I discovered that this fails if I haven't yet created a PlayerInput.
Does this mean that there are zero users by default, and that each instance of a PlayerInput you create makes a new user?
(that you create at the same time, at least)
I am moving this PlayerInput into a DDOL'd object that I created as the game starts, so that'll fix my issue
but I am curious about how this is working
I do not use it for anything other than getting access to an InputUser, actually...
ah, the user goes away when the PlayerInput component is destroyed!
I am a little surprised now, though -- the input system worked fine in my main menu (including when I was subscribing to and unsubscribing from InputActions directly
I guess actions can be performed even if there are no players?
there's gotta be a cleaner way to do this, right?
If your looking to reduce how many lines your toggling input, you can also call .Enable() / .Disable() on your playerControl.Player map, which will disable all actions on that Player map
How do I have more than one "north button" for mobile?
For me if I add two, they both will have the same function
How are you adding buttons?
Image > On-Screen Button
This frustrates me and I had to like bind some buttons to east and south and stuff
Now I have 3 buttons that dont work
you set them to different control paths if you want them to do different things
I have too many buttons for that
I take up the button north south east and west
Right and left joystick
you can literally start binding them to whatever you want
even Keyboard keys
mouse buttons
whatever
Just set the control path
Aren't you suppose to link the control path with the method in input manager
What is "input manager"?
no you linbk the control path with an input action in your input actions asset
that's the input action asset
you can bind keyboard keys to things there
there' s not a gamepad either
these are just virtual anyway
it doesn't matter at all
Will they work on mobile?
of course
Ok so if I want a new button
Wait
What do I set
Do I set the on screen button to random
Or the asset menu
wdym random
hello everyone, I am facing a bit of a challenge here. I am using Unity WebGL to create a webgame and i wanted to copy some text to the user's clipboard, how can I do that?
Write a javascript function to do it https://blog.openreplay.com/using-the-javascript-clipboard-api/
Interact with your javascript function via https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
Do i have to add this?
I need some guidance. I am using the new input system and have a Reload function. How can I add a delay when reloading so it reloads after like 3 secs.
I have made a Coroutine but dont know how to start it.
Make the reload method start the coroutine
Hey guys, im working in an inventory system and i'd like to be able to shift-click on some items and do things. I've tried this:
button.RegisterCallback<ClickEvent>(e =>
{
if (e.button == (int)MouseButton.LeftMouse && e.modifiers == EventModifiers.Shift)
{
OnShiftClicked();
}
if (e.button == (int)MouseButton.RightMouse)
{
OnRightClicked();
}
else
{
OnNormalClick();
}
});
}
using the UIElements, but it doesnt really work. Any way i could get this working using the new input system?
You probably want that second one to be an else if
Otherwise it's going to do both the shift click and the normal click
the thing is that it doesnt even enter the functions
i have some debug logs on them but they dont really print
Should I have a separate Action Map for different status conditions? (Example: Running, Swimming Underwater, Transformed, and First Person / Third Person controls)
That may be up to your games needs, though I would say different maps make sense when input could override actions that should only be allowed in specific conditions (like having a "driving" or "flying" map different from a "running/on-foot" map since yaw/pitch/roll can be controlled with movement keys for example) - or when you want to split input in a way that lets you toggle parts (such as having a map for weapons/shooting, and a different one for movement, this means you can disable the weapon map when in a car, or disable the movement map when in a cutscene, etc) - in general though, I usually have a main "player", "menu" and feature specific like weapons, driving, etc, I wouldnt have a different one for something like swimming and running, but maybe underwater works differently
Bug. Any help? If I touch on my samsung s23 ultra and untouch the touch still remains like invisibile cursor. In this test you can see. I used two finger and lifted up and it remeans like I would still touch it and buttons get hover states (twice because 2 fingers). Remember when they get red my fingers arebnot on the screen.
Any idea or fix?
EDIT: Tested with the old input system.. there it works. Not with the new one. I guess its a bug
I have a script that is using Mouse.current.position.ReadValue()
The script is working perfectly fine on my desktop, but when I switch to my laptop, it starts throwing a NullReferenceEception because there is no mouse plugged in.
Any clue how to fix this?
Check if Mouse.current exists? Or switch to the new input system?
That is the new input system
Your laptop doesn't have a mouse
so Mouse.current is null
you will want to check if you actually have a mouse before using it
Maybe consider using this instead: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/api/UnityEngine.InputSystem.Pointer.html#UnityEngine_InputSystem_Pointer_current
Or perhaps switch to the more robust approach of using Input Actions.
Would the pointer class cover a trackpad? It doesn’t look like it will according to the docs
Try it and see
Ok, I’ll let you know
It doesn’t, still giving a null
Hi guys, pretty confused about the new input system's rebinding feature here, the action to rebind is referenced by an InputActionReference, but the rebinds does not apply to the instance I created...
Was I meant to be using a specific instance somewhere? One that likely all InputActionReferences points to at default?
InputActionReferences point to... whatever you actually reference with them
the rebinding only applies to the specific actions you rebind in your code.
But they're set in the inspector
Which means that it had no way to know the instance I created at runtime
Yes, you assign them in the inspector to a specific thing
correct.
You wouldn't use IAR if you want to reference something you created at runtime
So the only logic is that either I fetch the runtime one and rebind that one, or there must be some sort of singleton somewhere that the InputActionReference references
Again it references whatever you set it to in the inspector
it's not a singleton
you chose to reference something
that's what it references
I fetch the runtime one and rebind that one,
If that's the one you're actually using for controls in your game, yes you would do this
Basically, was I meant to do this?
public static MainInput input;
void Awake()
{
input = new MainInput();
}
wdym by "was I meant to"?
Ok but what do you mean by "meant to"? There are many ways to use the input system. This is one of them
Well yeah you would have to pass this reference to the code that does the rebinding
And the InputActionReference's reference can be run normally, so it must be an instance in of itself
The instance is whatever thing you referred to in the inspector.
and yes, every copy of the actions asset is an instance, of course.
by definition
So I'm questioning whether this way of creating new instances was meant for splitscreen type stuff, while there's actually a main somewhere
The main approach for splitscreen is to use PlayerInput/PlayerInputManager
but you could do this for splitscreen if you want to
again the system is flexible, and you can use it however you wish
So... In a nutshell, this is normal, right?
public InputActionReference inputAction;
InputAction action = GlobalPlayer.input.Player.Get().actions.Single((InputAction action) => action.name == inputAction.action.name);
InputActionRebindingExtensions.RebindingOperation rebindOperation = action.PerformInteractiveRebinding(bindingIndex).Start();
Essentially I'm fetching the action with the same name as the one assigned
There isn't really a "normal". If GlobalPlayer.input.Player.Get().actions is how you fetch your instance of the actions asset that your code is using, then sure this is the way to do it.
I would guess it's more likely that GlobalPlayer.input.actionsAsset or whatevert is a simpler way to get at it though
Don't remmember exactly if that's what it's called on the generated C# asset or not
get a reference to the InputActionsAsset
But I don't really know what all the pieces of GlobalPlayer.input.Player are because this is your specific project code that I'm not familiar with
so I'm making educated guesses here
GlobalPlayer = PersistentPlayer, a singleton
.input = A new instance of MainInput created on Awake
.Player = The name of one of the actionMaps
Uh, now that I think about it, I shouldn't assume the action map used
OI assume MainInput is the name of your INput Actions asset and the generated C# class created from it
Yes
if you want a specific action from a string it's basically myInputActionAsset["MapName/ActionName"]
Ah, I see, InputActionAssets is a dictionary?
ight, looked like dictionary logic
Yes Dictionaries have indexers too
so they both use indexer syntax
Whelp, I'll go research again ig, thanks Praetor, see yah
Quick test, this asset is accessible by MainInput.asset (MainInput => instance of whatever the generated class is called)
Just correction cus it's not called actionsAsset
Ok thank you
I don't have a Unity project in front of my so I couldn't check, and that doesn't happen to be documented 😓
I've got an odd issue where the InputSystem isn't correctly observing gamepad or keyboard inputs (Not allowing any input through unless it is a joystick Vector2 movement) until InputDebugger is open. Does anyone know why this is?
it only seems to happen when in unity editor, not in-game on build versions.
Hey guys
How do I make my unity game accessible for mobile so you can move touch buttons and other things
Look up onscreen controls in the new input system
do anyone know how to add crafting into my vr survival game?
With a large amount of effort and planning
Is this even close to what I'd need to create a controller to tell apart between a tap, a hold and a drag? Basically I want three separate abilities to activate depending on the input type (on tap turn on the light, on hold a focused ability, on drag a conical AoE - I also want to be able to tap a different area for a different ability). My question is can I tell this behaviour apart in the input system or should I just listen for "touch" and "hold" separately and then figure things out from there?
Drag definitely needs to be separate.
For tap and hold I would do it with one action with the default interaction, especially if you don't want the tap thing happening when you hold
with this setup, both tap and hold will happen when you hold
You'll want to handle the disambiguation in code
Makes sense - so when I have two separate actions (tap/hold and drag) there's no way for both to fire at once?
what do you mean by "at once"?
They can all independently fire
they don't care or know about each other
As in will everytime I "Drag" automatically trigger the "tap or hold" since the latter is a pre-requisite for the former?
that will trigger when you press the mouse button and release the mouse button
the drag one will trigger when you move the mouse
they're independent
So dragging is moving with the mouse held down? Which is the same as the "hold"? I'm probably completely misunderstanding something 😅
drag is just the name you gave your action
The action is bound to the mouse position
so it cares only about mouse position
Ah, yeah makes sense, I set that wrong for sure then, I thought that defining "hold" in interaction also means it's held down, not just moving the mouse around
you definitely don't want a hold interaction there
it makes no sense
no it's not that clever. That would make it trigger only if you continually move the mouse for .5 seconds
it really just doesn't make sense outside of button style controls
Ah! Welp, I completely misunderstood it then - time to re-read the docs - thanks! 🙌
Hello,
I have more than one action map and trying to switching between maps by A.Enable() B.Disable() and vice versa.
But then pressing the key that disables current map and enables the other one actually fires another action in the second map that uses the same keybind. (seems like it is not consumed by the first action map & seems like it is intended)
Can anybody help me out with this issue? What is the proper way of handling this?
one workaround is just to wait a frame before enabling the other map with a coroutine
I see. I should try that, thanks.
MY INSPECTOR TAB IS BLANK I DONT KNOW WHAT TO DOOO
This is not an #🖱️┃input-system issue, and see #📖┃code-of-conduct , don't write in all caps
well im annoyed
That has, suprisingly, no relevance to whether you should BE annoying to others or break the rules
How about stop being rude I just need help
You were helped. It was a very simple issue.
I was objectively not rude. But screaming in caps in the wrong channel and thinking your issue is more important than the rules IS objectively rude
This may help with similar issues in the future. Very clear descriptions of every part of the editor with a diagram
https://learn.unity.com/tutorial/explore-the-unity-editor-1#6273f00fedbc2a7f158cc1ee
Can someone help me figure out why my gamepad isn't registering as connected for my project? I haven't opened this project on this computer before and when I did I had some errors, resolved them, but now I can't use my gamepad/ controller as input.
can I "inject" inputs to the input system?
Say, my game uses actions and the input system and it's all happy.
I want to add touch controls.
Can I "inject" the virtual touchscreen joystick into the input system so the rest of the game remains all happy?
Look up "on screen controls" in the new input system
I have SCUF envision pro. Why isn't it being detected by Unity as a connected Gamepad?
Have you tried the input debugger?
Is there something specific in the input debugger window I should do?
Check to see if and how your device is detected and recognized
Its is recognized as an unsupported controller
That it just won't work?
you can see what events it fires as you press buttons etc
Where do you see that?
I read the documentation page and don't understand how that helps
The Events section lists all input events generated by the Device. You can double-click any event in the list to inspect the full Device state at the time the event occurred. To get a side-by-side difference between the state of the Device at different points in time, select multiple events, right-click them, and click Compare from the context menu.
Did you read this part
Yes. 2 problems with that section. 1 when I double click on the controller nothing happens. No event modal pops up. 2. Its not registering the controller as a valid device in some sections and in other sections it is. For example the console log shows it as an xbox 360 controller when i unplug and plug it in:
Alright well you've reached the limit of what I know about device handling
Well thanks for the attempt
I have this line
context.action.bindings[1].effectivePath This works, but as an example, for gamepads, it shows the "general" binding i.e Gamepad/buttonEast. If i wanted to get the exact binding (i.e Xbox/B or DS4/O) would i need to create a different control scheme for each device?
It wasn’t
It wasn't a simple issue? You had simply not selected something. You of course have to select something to inspect it.
Either way, there is no need to continue this. Please just respect the community and others, don't be rude, and follow the rules
https://learn.unity.com/ has the essentials pathway which will get you going quickly. It will teach you all about the editor.
All the other pathways are great too
Your being rude tho. you don't need to talk
I have a UnityEngine.InputSystem.InputBinding object. when i call "ToDisplayString()" on a button south input on it my xbox controller returns "A" which is great, I'm then using that string to convert it to the corresponding character in promptfont. I don't own a PlayStation controller so I don't know what would be returned on that controller. does anyone know how ToDisplayString would be translated for each of the 4 main buttons (north button, south button, east button, and west button)? I cant seem to find it the docs.
How can you have these two inputs for the same action? I tried using Any for the control type, but no luck getting it to work. I can just make two separate actions, but was hoping to figure this out.
Left stick (up)
Keyboard W
I want both to move the character forward, but I wan the left stick up to function like a button since I have grid movement in my game where the player moves one unit forward.
**
NVM I'm an idiot I thought I had selected left stick UP as the input, but I only selected left stick. **
I can't for the life of me figure out how to get the current used device from an input action asset, without using playerInput. Is there an easy clean way?
Just add them both as bindings to the action
should i have only one instance of my actionAsset? Cause since now i've been just insanciating a new one in each script where i need em but maybe that's bad practice?
It's good to have just one if possible so you can do rebinding and enabling/disabling actions from a central place
that makes sense thanks
Hi, I am working with unity 6.
I was wondering what the best approach for making an asset is.
What I mean is, I have my utils asset which shouldn't be tied to a project, and therefore should have it's own actions asset.
Having a single actions asset doesn't seem like a good approach because that would mean I(or anyone else using my utils) would have to create a new action map for each project to add all the needed actions.
The issue is, when I created a new actions asset, it didn't work(I assume because it's not a project wide input system asset) and I don't know what I am supposed to do now.
Thanks in advance!
What I mean is, I have my utils asset which shouldn't be tied to a project, and therefore should have it's own actions asset.
Make a UPM package containing your stuff.
The issue is, when I created a new actions asset, it didn't work(I assume because it's not a project wide input system asset) and I don't know what I am supposed to do now.
What do you mean by this? what did you expect it to do? What steps did you take to try to make it work?
- I am using git, much easier than having to constantly package and upload it, I can just push changes from the latest project I am working on.
- I don't know how input systems work behind the scenes, I was hoping that doing something like
if (_backAction.action.WasReleasedThisFrame())would check if one of the back action inputs was released that frame.
What I did was:
- Create a new input system actions asset
- Get a reference to an action from it
[SerializeField] private InputActionReference _backAction; - Tried and failed to use it
I don't know how input systems work behind the scenes, I was hoping that doing something like if (_backAction.action.WasReleasedThisFrame()) would check if one of the back action inputs was released that frame.
Yes it will do that.
Tried and failed to use it
What happened when you tried? Did you remember to call.Enable()on it to enable it?
I didn't do that, is there a way to have it enabled by default?
I don't have a manager or anything like that for my utils asset where I could call this from just once.
If you didn't enable it that's why it's not working
is there a way to have it enabled by default?
Not really
I'm running into an issue I think is an input system issue, but I'm not 100% sure what the deal is. I have it set up where I walk up to an item and hit the button I've labeled for interact, and it pulls up a menu with 4 buttons i can select from. If I use the keyboard, hitting E pulls up the menu, but using a controller, it pulls up the menu and selects the first option immediately and I can't for the life of me figure out what the deal is and why it's acting this way.
Anybody have any insights? For the input system I have it set to trigger on context started, that should only fire once, shouldn't it?
I have the first button set up in the script to use SetSelectedGameObject so that's why it's choosing the first one, but again it's only doing it using a controller
Is the button you use to interact on controller also the submit button for your ui input module?
That seems likely
It was, I removed the submit from the UI and it was still happening
I removed the submit from the UI
How?
wdym by that
I opened up the input actions I made, went to UI and removed the gamepad option from submit so the only remaining thing is just the keyboard
Which input actions are you using for the input module though\
I'm not quite following what you mean honestly, I downloaded the package, made a new input module in my assets and set the bindings in there, one for player, and one for UI
THe UI Input Module
it's a component on your Event System
it's the thing that hooks up your input to the UI system (aka pressing buttons)
If you didn't do anything with that, it's using the default asset
which has probably "Button South" as the submit button
which is likely what you're pressing
For vector2D movement, how can I compensate for when a diagonal direction is released (say UP and Right keys pressed) since you cant release them at the same time. I need to save the last direction the character is facing, but need to compensate for this delay and count it as a diagonal vs one or the other input direction.
Perhaps you can separate horizontal and vertical inputs
so you track them separately
each one gets reset to 0 if there's no input in that direction and there is input in the other direction
and then give that reset a slight delay
Comes down to either:
- Adding a delay logic of some kind
- Adding some kind of interpolation to the rotation change, i.e. make it not instant.
not sure where to ask this, but is there a way to tell when the mouse is over a UIToolkit ui so I know to ignore it as a mousepress in the game?
Use the event system for your in game mouse clicks and you'll get this for free
In the UI docs.
You'll want to use the EventTrigger component or implement these interfaces yourself on your 3D objects: https://docs.unity3d.com/Packages/com.unity.ugui@2.0/manual/SupportedEvents.html
You'll also need a PhysicsRaycaster (or the 2D version) on the camera
what is a good way to troubleshoot slowdowns of the input system?
Same way you troubleshoot any performance issue - use the profiler
Btw, you are not using the Input System, you are using the Input class.
The InputSystem is a newer thing.
But yeah, looks like you got it resolved in #💻┃code-beginner ? Just gotta scale it by deltaTime
Yesss
Hi it's me again with the same issue as last night: I've replaced the actions asset in the EventSystem with my own action map, however I'm still running into the issue where the button to interact with something is the same button that is submit for the UI that pops up and chooses the first button immediately. Is there a way to make it so when you change to another action map it doesn't recognize a button that's already pressed down?
Wait a frame before you enable the new action map
I'll give that a try, thanks for the help!
That didn't work, it seems like Submit is triggering when the button is held down no matter what, but I could probably just do a WaitForSeconds(.1f) or something
Otherwise I suppose I can do a check if the button is pressed and if it is just have it wait until it's released and then swap the map
Hey there
I got probably a rather trivial problem rn which I cant get my head around.
How do I get a continuous call to methods from the performed ?
Or do I need to get back to Update/Fixedupdate
The input system is for handling input events
if you want sometjing to happen every frame or every physics frame, that's what Update/FixedUpdate are for
Alright, I changed the call towards the Update now.
Thanks for the advice :)
I have a problem, when I place 2 player inputs, it only recognizes 1, what happens is the following, I downloaded the Unity character controller and it uses the new input system with the behavior of send messages and I have another player input that I use to that recognizes the Xbox buttons, so I don't know how to combine them since the Unity one is a labyrinth how send messages uses it, is there any way to make the 2 player inputs work at the same time?
1 PlayerInput per human player
If you use more it will expect to connect to more input devices
hello i have a ps3 controller and i want to add controller support to my game will it work the same for other controllers even if i test with a ps3 controller
Use new input system
You can find the new Input System under "Package Manager > Unity Registry > Input System"
thanks so if i choose gamepad it will work the same on all controllers
Most
Hey guys, any idea why on the gamepad im getting 2 calls with context performed? On a keyboard its called only 1 time (as i'd like it to), it's normal button (in the action map) + method call in the unity event in player input. Also it's normal button (A xbox) not trigger
Pass through seems to work the same way
You sure it's performed only? Show your code?
Especially how you hooked up your listener
instance id looks the same with both calls, and in events i have only called it once
gameObject.GetInstanceID()
-2864592
gameObject.GetInstanceID()
-2864592
what could i log in Debug.log that'd be helpful for us?
One of these is OnBeforeInitialUpdate
Maybe something with "initial state check"?
Not sure
also not sure what could i look here for
i think ill just do float lastTimeCalled, and check if its called second time the same frame, cuz i dont know what to do with it rn 🤷♂️
I was referring to the initial state check setting on the input action
this one?
Ok, i change a map later on in the CurrentSelect?.Cancel(); and it call all events second time (started, performed, canceled). But i wasn't aware that it calls all of them even if you change to the same map for example ui into ui.
@austere grotto thanks for your help 🙂
Although, i'm still curious why my keyboard was called only once 😄
Does anyone know why Unity made the Control Scheme device selection list view use right clicks for interaction instead of left clicks, which they use everywhere else in Unity?
Is there a way to utilize the new input system in Unity without having to implement OnEnable and OnDisable in the scripts?
Yeah. SendMessage instead of events
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour {
private MainManager mainManager;
private PlayerInputActions inputActions;
public bool isPaused = false;
private const string MAINMENUSCENE_NAME = "MainMenu";
private void Start() {
mainManager = FindObjectOfType<MainManager>().mainManager;
inputActions = new PlayerInputActions();
inputActions.PlayerBasicMovement.Pause.performed += Pause;
GetComponent<Canvas>().enabled = false;
}
public void Pause(InputAction.CallbackContext context) {
Debug.Log("Triggered outer");
if (context.performed) {
Debug.Log("Triggered inner");
if (isPaused) {
Time.timeScale = 1.0f;
GetComponent<Canvas>().enabled = true;
}
else if (!isPaused) {
Time.timeScale = 0f;
GetComponent<Canvas>().enabled = false;
FindObjectOfType<SettingsMenu>().gameObject.SetActive(false);
}
isPaused = !isPaused;
}
}
}```
what is missing in my script that I cannot trigger the Pause() function? Can anyone help?
you have not enabled any input actions
you can do inputActions.PlayerBasicMovement.Enable(); to turn on the entire map
So in PlayerInput enable is not required but outside of the player controller it is?
when using input actions
I don't know what you mean by the "PlayerInput enable"
public PlayerInput playerInput;
public InputAction moveAction;
private CharacterController controller;
public bool playerLookable = false;
public bool playerMoveable = false;
private void Awake() {
controller = GetComponent<CharacterController>();
playerInput = GetComponent<PlayerInput>();
moveAction = playerInput.actions.FindAction("Move");
currentSpeed = baseSpeed;
}```
this is my code on the upper map "move"
used on the player with a PlayerInput component
I didn't write a line to explicitly Enable the map but it worked
the PlayerInput component will, by default, pick a single input action map and enable it
oh, It worked
appreciated for the tip
oh I see there is a default map dropdown in the PlayerInput component
that's why it worked without me enable the map
public void Pause(InputAction.CallbackContext context) {
if (context.performed) {
isPaused = !isPaused;
if (isPaused) {
Time.timeScale = 1.0f;
GetComponent<Canvas>().enabled = true;
}
else if (!isPaused) {
Time.timeScale = 0f;
GetComponent<Canvas>().enabled = false;
FindObjectOfType<SettingsMenu>().gameObject.SetActive(false);
}
}
}
public void PauseButtonDown() {
var context = new InputAction.CallbackContext();
Pause(context);
}
how can I do to make the pause function work through the PauseButtonDown() which attached to a button onclick event
for now I guess my new context does not passes a performed message and I cannot edit it like context.performed = true since performed is readonly
Is using a private event that links both ways of pausing to the function a better way?
you do not create your own callback context
I'd rearrange this so that it's:
void PauseAction(InputAction.CallbackContext ctx) { Pause(); }
public void PauseButton() { Pause(); }
void Pause() { /* pause code in here */ }
oh, I found that making a event for this is excessive, just call another method
thanks for the help
hello, Im tryin to broaden my knowledge of the new input system, and im trying to get an action to have 2 interactions on it, hold and tap, hold will drain water, and tap will pickup or drop the item.
This may be wrong, but it works for the hold interaction atm
public void OnInteract(InputAction.CallbackContext context)
{
if (context.performed)
InteractAct = context.ReadValueAsButton();
if (context.canceled)
InteractAct = false;
}
How would I implement a tap feature without stepping over the hold feature?
I would stick with the default interaction and handle everything in code. You'll basically need to implement a small state machine.
Basically you have these states:
WaitingForInitialTap
WaitingForReleaseOrHold -> if release before time threshold, do the Tap action
v
if time threshold gets reached ebfore release - do the hold action
I wouldn't formalize it with multiple classes or anything
im gonna mark this for later use XD
okay, Im trying to go about making this game slowly, and methodically, but the problem you get with keeping it clean and modular is the confusion, and complexity
You could actually model this as one action with the Hold interaction maybe and do this:
bool wasPerformed;
public void OnInteract(InputAction.CallbackContext context)
{
if (context.performed) {
// Hold timer was reached
wasPerformed = true
DoHoldAction();
}
if (context.canceled) {
if (!wasPerformed) {
// This means we released the key before hold timer was reached.
DoTapAction();
}
wasPerformed = false;
}
}```
then just set the hold time as desired in the Hold interaction
Im worried about turning my input class into a class that does something and calls its own methods. Im scared of the speget
have it fire events
other things can handle the events
bool wasPerformed;
public void OnInteract(InputAction.CallbackContext context)
{
if (context.performed) {
// Hold timer was reached
wasPerformed = true
OnInteractHeld?.Invoke();
}
if (context.canceled) {
if (!wasPerformed) {
// This means we released the key before hold timer was reached.
OnInteractTapped?.Invoke();
}
wasPerformed = false;
}
}```
i DIDDD i diddd DXX and that started to not workkk lolll using events was great but the idea of it for me was to make code more independent. In reality i still needed those scripts to connect, and did away with events after that
events reverse the dependency that's all
Instead of A knowing about B to call B.Something, now B knows about A to listen to A.OnSomeEvent
you still need the scripts to connect in any case
YOu can make the events static if you want.
I think i dont know enough about events to use them properly. I had it used correctly but then didnt know what i was really doing with it
Regardless this is an unrelated discussion
However you want to communicate this stuff to another script is different from how to handle the logic
yea u right, and i didnt think about it that way :o, thanku good sir
So I'm using the new input system and have 'held' for a button, however, when I try this code (I'm sure this is a logic error?) the moveDelay doesn't do anything even if I set it to a ridiculously high number. However, if I remove the moveDelay movement is instant.
private void Update()
{
BasicMove();
}
private void AttemptMove(Vector2 moveInput)
{
// Movement stuff
isMoving = true;
StartCoroutine(MoveCooldown());
}
private void BasicMove()
{
Vector2 move = playerControls.Gameplay.Move.ReadValue<Vector2>();
if (!isMoving && move.magnitude > 0.5f)
{
// Prevent diagonal movement
if (!(Mathf.Abs(move.x) > 0.5f && Mathf.Abs(move.y) > 0.5f))
{
AttemptMove(new Vector2(move.x, move.y));
}
}
}
private IEnumerator MoveCooldown()
{
yield return new WaitForSeconds(moveDelay);
isMoving = false; // Reset moving flag after moveDelay
}
Any ideas?
I figured it out, I am a HUGE DUM DUM and moveDelay was a public float that was being overridden by the gameobject.
How come the new input system doesn't need to be put in update?
controls.Main.Movement.performed += ctx => Move(ctx.ReadValue<Vector2>());
Because it is event based
Not polling based
Although you CAN do polling (Keyboard.current.AKey.isPressed or whatever the syntax is for that. Maybe IsPressed() can't remember off the top of my head)
Interesting... thank you for the info
it can be put in Update
it can also be event based
it's very flexible
So I install the Simple Demo from the Unity Input System samples and play the SimpleDemo_UsingPlayerInput scene: work as normal and can control the Player. Now I remove the SimpleController_UsingPlayerInput component from the Player and add it again then play the scene: can't control the player, why?
Isn't that the script that controls the player?
yes
Kinda like " I took the engine out of my car, why did it stop driving?"
It probably needs to be configured in the inspector somehow
And other things might have referenced it as well
So you broke all that stuff by removing it
I put in the same values of the variables
The is the other part
Most likely the PlayerInput component itself
But impossible to say for sure without seeing it
if I compare it to the unmodified scene it has the same parameters
What does
PlayerInput
ok I found the problem
removing the controller script removed these entries
thanks
Yes indeed
Can someone help me out here? When I use context.performed to read this input, it always fires instantly, no matter what I set the "Hold time" to.
you have it set to Pass Through
so it basically ignores any interactions iirc
it also happens on Button and Value type too.
show how you hooked this up to the code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This doesn't show how it's hooked to the code though. In the inspector in Unity Events mode? And how are you checking when it fires?
YEah, it's set up in inspector, and I'm using a Debug.Log set to track the clickheld variable.
where are you logging? I didn't see it in the code you shared.
https://hastebin.com/share/boketekefe.csharp
Here, added a second check to the input manager itself, re-tested it, and confirmed that it's still firing every frame that the mouse is held down (Ignoring any delay put into the Hold Interaction)
And here's a screencap, showing without a doubt that the Input Manager is correctly hooked up to the ClickHeld input.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I still don't see a Debug.Log in ClickHeldPressed at all
I only see one in ClickDownPressed
Why don't ypou put a log in ClickHeldPressed itself
to tell you exactly when performed is happening
that's what we care about
Update is confusing things
https://hastebin.com/share/biyuvoweta.csharp
Edited, tested, spamclicked, and this was the result and here is the edited version with Debug Logs for each
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
- Make the hold time like 5 seconds (would this be 5000?)
- Remove all the bindings except the mouse for the moment.
- Also show the mouse binding screenshot
With 50000 as the hold time, all bindings set to no function except for ClickHeld, and screenshots/gifs of everything including spam clicking
Anything stand out?
dumb question have you saved the asset
oh also
you need to remove the "Press Only" interaction from the mouse
Yes
that's prob ably overriding the Hold interaction on the action
That finally fixed it
Thank you very much, and I apologize for using up so much of your time!
Bind an action to the mouse click
Is there a shortcut or something if I want to right click
What do you mean shortcut? Just bind the right click
I found something like this, Mouse.current.WasClickedThisFrame
Ok, yeah if you want to poll it, you can do that
Mouse.current.leftButton.wasPressedThisFrame
Sure but you miss most of the benefits of the input system like that.
It's ok if you know you'll never rebind it or anything
This is of course the leftButton, not right
I have rebind for other stuff like E for interact
Or support touch etc
😅
But this is a valid solution right?
So for my case it's ok
I don't know your case
These are all valid approaches: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/Workflows.html
You're doing the first one
I wonder if the "new input system" ever going to not be new.
Has anyone had any success having two different keyboard schemes? I want wasd and arrows to be different schemes so they can be used for player 1 and player 2. but with auto join, when I hit the arrow keys, it joins with the wasd scheme.
it kind of seems like hitting any key causes the player to join with the first keyboard scheme.
is it possible to set which keys cause which schemes to join?
Good thread on the topic. It requires a small workaround
https://forum.unity.com/threads/multiple-players-on-keyboard-new-input-system.725834/
Hello,
I'm trying to make a local multiplayer on the keyboard.
I made it work with the joysticks to create a new player when pressed a button, but on...
Thanks!
I can't seem to find any information about this but is it possible to target the steam deck control opportunities specifically?
Is it possible to prevent a specific action (like mouse position) from causing auto join or auto switch?
how to make something like jump when holding jump higher with new input system?
I've been having a problem that I can't solve for a while...
I've tried many different things but they don't work, the result is always the same error when this case occurs: in a 2d mobile game, having created a new input system action that is simply left click, when it is pressed many times in a row (many clicks in a very short time) the value of that action remains stuck at 1 (ReadValue<float> = 1) even though the button is not being pressed. Also printed IsPressed, and it is true while not holding the button.
I've tried almost everything, different types of Coldown systems using Time.time, coroutines that disable the button and activate it every time it is pressed, different types of FSM, restrictive bools of various types, setting the action to Button or Passthrough with or without Initial State Check checked, I tried to use the instruction Reset() of the action after using it...
The only "solution" is to set a Hold Processor on the action with a value of at least 0.5, but it is useless as it breaks the experience. I don't know what else to try to prevent the button from getting stuck with value 1 when pressed very quickly. Any solution? Thanks
It does not depend on the input system, if you want to jump higher when holding a button just add a bigger force to CharacterController or Rigidbody. Also, check Processor/Hold in the new input system, so the function Jump is performed while the button is pressed
Is your button probably firing a script that just causes the error if executed too many times?
Testing out Unity 6. During dev, no errors when playing. But when I build, the errors come up the moment player loads and these are the only ones. Everything in the player works proper, no issues with actual input.
In the player log is there more to those messages?
here is a snippet or the first one. The rest follow the same pattern:
any thoughts?
How do I add WASD support for my player movement? currently since its a vector 2 for stick support, keyboard is not listed as an option since its a different kind of input
Is there a way to make the input event trigger each frame when a button is held? Seems like the event only triggers when the control state changes, but I'd like to do some repeat logic as long as the button is held
If you want to run something continuously, you should just call IsPressed() on the action itself
you can use InputActionReference to assign a reference to an input action from an asset
or, if you're using the "generate C# class" feature, you've got all of the actions right there
ah ok, I was hoping there was a way to get the event to trigger each frame like in unreal, but looks like not. Thanks for the info!
you could always detect button press and release and use a coroutine
Yeah I put together a little timer system to handle things, seems to be working well so far
i have a problem that the Listen button is hidden behind other ui elements. it's still possible to click it, but it's hard. another problem is that when i press binding, it makes my cursor behave as if i was typing something, while i'm not typing anything. it makes it hard to press the bindings and i need to press the binding on a specific spot for it to work. there's also this warning upon installing the new input system: Unable to find style 'ToolbarSeachTextField' in skin 'DarkSkin' Used UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
Whats the best way to handle the input system across multiple scenes?
depends on your needs
I dont think so, the Action related to the button is only used in the Input Script
is there a way to get what generic type of controller the user is using? I want to get if they're using an Xbox Controller, a PS Controller, or a Switch Controller
I have gotten this issue before, its due to a caching problem containing a typo in that style name, this post should help fix it: #🖱️┃input-system message
thank you
I'm using an on-screen joystick to make the player aim and attack on release
But for some reason despite the player turning when I tap shortly, it doesn't actually attack whatsoever
Which I believe to be cus of WasReleasedThisFrame... However I have no idea about why this is happening
you'd have to show your code and how the action is set up and how the code is hooked up to the action etc
I figured another detail out, I was mistaken
It seems to work when you press the outer parts of the joystick
But won't work if you tap close to the center
Unfortunately I can't right now
I have a build of my game on my mobile, that's all I can test on rn
WasReleasedThisFrame is really intended for button actions
Ah...
it will work for a joystick but only when you go from the default actuation point (maybe 50%) to 0
So uh... Caching whether it's not zero last frame and comparing to this frame every frame?
Cus I see no other way if I try to do it by the vector value
I'm currently using the code below for mobile input, and by using the mobile simulator, using the Left mouse button click it works fine, however, let's say I want to use the Right mouse button click, how could I make it work for the simulator?
if (Touchscreen.current.primaryTouch.press.isPressed && Touchscreen.current != null)
why would you do this, on a mobile device you wont have a right click, you should be using https://docs.unity3d.com/ScriptReference/Touch-phase.html
Thank you for the reply. I wanted it to be able to test through the PC. But nevermind, I found a solution
I'm using Unity newest version, and I have a mobile simulator system. And the setup at the image only works for the mobile simulator window, why doesn't it work for the game window mode? I also think that in the game window it only works codes using the old input system, while the mobile simulator window only works the new input system. Anyone knows why that is?
Do I need to change anything here?
Hey,
Im gonna work on a 2D topdown game in Unity.
Im experienced with coding, just not all to much with C# yet. (about a year)
Is it recommended to use the old or new input system?
(PC Steam Game)
If you are new to Unity and you don't need:
- rebindable keys
- local multiplayer
I would stick with the old system as it's simpler
If you want to have local multiplayer or rebindable keys, the new system is worth learning
But the learning curve is steeper
im gonna use Photon to implement server based multiplayer tho
but also, for local multiplayer, will the old input system cause issues ?
Only local multiplayer will get benefits.
It's just harder to work with
If someone has the time to take a look at this post of mine on the forum, I would be very thankful.
https://forum.unity.com/threads/playerinputmanager-doesnt-manage-my-spawnpoints-properly.1603842/
Hi, I created this script to manage a local coop game following the video below. As far as I manage to find out, the PlayerInputManager is somehow...
Hey all, is there a way to "remove" selectables from the Event System so they're not valid for selection (e.g. with a gamepad nav)
I don't want to disable them or them to appear deselected, so canvas group interactable won't work
maybe disabling their Navigation is the only way?
set up navigation manually is your best bet IMO
I'm using the input system rebinding extension, is there a way to discretely detect scroll wheel up and scroll wheel down as independent inputs when using PerformInteractiveRebinding()
regardless of which direction i scroll, it gives me the same input action, "Scroll Up/Down"
i need both inputs to be discrete from eachother so that the player can bind swapping weapons forward and backward to two discrete buttons or to the scroll wheel
otherwise id either be forcing the player to bind swapping weapons to an axis, like the scroll wheel, or making the scroll wheel swap weapons forward/backward regardless of which direction you scroll
if (m_Operation != null)
{
m_Operation.Dispose();
m_Operation = null;
}
m_RealAction.Disable();
m_Operation = m_RealAction.PerformInteractiveRebinding();
if (!string.IsNullOrEmpty(CompositeActionPart))
{
var bindingIdx = m_RealAction.bindings.IndexOf(x => x.isPartOfComposite && x.name == CompositeActionPart);
m_Operation.WithTargetBinding(bindingIdx);
}
m_Operation.WithCancelingThrough("<Keyboard>/escape");
m_Operation.OnComplete((x) =>
{
m_RealAction.Enable();
ButtonContent.SetText($"{x.selectedControl.displayName}");
x.Dispose();
m_Operation = null;
}).Start();```
if i debug on OnComplete, the selectedControl is Axis/Mouse/ScrollY. Is there a way i can detect the value (positive or negative) of that scroll and then set the selectedControl to the appropriate discrete ScrollUp or ScrollDown InputControl?
is there any way to get the context using the inputValue using Send Messages?
No, you would have to use unity events or c# events
I was afraid that would be the answer, thank you
Hey is there a way to hide an input control object on a class that inherits from gamepad
specifically I’m trying to hide the left and right stick buttons since my controller I’m added dosent have them
Both are viable. PlayerInput and PlayerInputManager give a really convenient start if you're trying to do local multiplayer
You'll have to do less work with device and user management that way
Anyone ever had these errors in standalone player log?
Action count in old and new state must be the same
Map count in old and new state must be the same
Binding count in old and new state must be the same
This occurs immediately after splash screen.
I confirmed via debugger that the UI InputAction is indeed enabled. I also confirmed that any overlays are not raycast targets. But nothing happens with the buttons when I click them. On editor it works and I get no errors. But on standalone I get these errors.
Do you create your own actions or action maps through code at any point?
No. But I got the error to go away when I removed the part in my code that instantiates the event system from addressable when the app loads.
So it seems to be something with that. I'm gonna add it to the title scene hierarchy and build and see if it happens again.
It worked. So it's and issue with me loading it from addressable.
Here is how I load it:
private static GameObject _LoadAndInstantiateResource(string resourceKey)
{
var assetHandle = Addressables.LoadAssetAsync<GameObject>(resourceKey);
var gameObject = Object.Instantiate(assetHandle.WaitForCompletion());
gameObject.name = resourceKey;
Object.DontDestroyOnLoad(gameObject);
Addressables.Release(assetHandle);
return gameObject;
}
Interesting -- I also instantiate my event system very early on
when exactly do you do it?
At first I did it Before splash screen load. But then I tried after scene load. Same issue.
mine gets created in a [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] method
Is it because I Addressables.Release(assetHandle);?
I should check that this isn't showing up in my built game logs
I would not expect that, no
(unity 2023.2.20f1)
🤦♂️
I didn't confirm it worked AfterSceneLoad because it was AfterAssembliesLoaded. I changed it to BeforeSceneLoad and now it all works.
interesting!
Thank you for engaging, this helped me figure out this problem.
I picked this pretty arbitrarily
lol
I'm using the old input system, and I'm having an issue with getting input from the e key consistently. It isn't a problem with the keyboard, since it works regularly). I've tested using Input.GetKeyDown and Input.GetButtonDown with a button set up in the input manager, and both ways only work about one in 5 times.
Never mind, it was because I had it in FixedUpdate instead of Update.
I want to know that how can I use the tilt or change in rotation of a mobile device to accelerate and turn my player using new Input system. Can someone help me know which option should I use?
yes, both input systems can handle gyroscope and acceleraometer inputs
Is there a means to serialize a reference to an action map?
I'd like to expose a property on a MonoBehaviour to specify a map, but the best I have come up with is just punching the map's name into a string field and looking it up from the asset within the code. It's perfectly functional, but... eww... strings.
I guess I could also derive it from a random action assigned to an InputActionReference property
how can I detect when a button is pressed using an InputActionReference?
For some reason whenever im testing controller input, i have to restart my unity, then the controller works on the first time i run the game, then if I stop and re run the game the input is just nonexistent again and I have to restart my editor again to get it back. Is this a hardware issue?
Thanks
What controller is it? Like something rare custom whatever?
Poll the action in Update or subscribe to its performed event
Its a dualshock 4
Ps4 controller
So for additive scene loading do all the scenes you may want to load/unload need to be in the main scene when the game starts or can they be added in at runtime like instantiation?
no they don't have to be in the main scene. They are separate scenes
that's the point of loading a scene
they do need to be in build settings though
can i use an external button in my game ?
we are team and we want to make IOT button and we want our game read a signal from our button can we do it ?
and How?
Sure why not. Use HTTP to communicate, as you would with anything on the Internet
Not an input system related question TBH
thanks
Im trying to write a rebinding menu for my game, using unity's new input system and the input rebinding extension. How can i filter the individual directions of an axis input within PerformInteractiveRebinding() so that i can assign them to the positive and negative part of a composite input?
for instance, movement left and right is a composite input with a positive and negative direction
if i input the left analog stick into one of these, the binding is set to "Left Stick X", which just triggers that direction of the composite input regardless of which horizontal direction i move the analog stick
what i would need is to filter it to something like Left Stick/Left or Left Stick/Right instead of just Left Stick X, depending on the direction the player inputs
the same applies to scroll wheel inputs, any direction on the scroll wheel will set the binding to Scroll Up/Down, instead of the actual direction the scroll wheel was rotated
anybody have any ideas for this? I could not get it working with my ps4 controller (more than 1 run) so i thought maybe it was the chord since my chord was a bit finnicky, i tried a new chord, same thing. Then i tried using one of my xbox controllers. wont even get the input. Even though it works completely fine in joy.cpl / online gamepad testers and is clearly connected, for some reason the editor is not detecting it. All ideas are appreciated I have scowered the internet
so here's a bit of a long shot
Valve has an input system called Steam Input
I'm wondering if anyone has ever looked at using it as a device
Steam Input lets you declare actions like "Shoot" or "Dodge" and have those appear directly in the input configuration in Steam
So in theory, you could create an input device that responds to these actions
so if I had an input action called Dodge, it might have bindings of:
- Shift (Keyboard)
- Button South (Gamepad)
- Dodge (Steam)
Any reason why my controller input works perfectly fine in the editor, then in the build it does not get detected at all? I have no errors in the build, just nothing happens when I start inputting stuff on the controller, keyboard/mouse still works fine. I have been researching this for a while and none of the known fixes (the few that exist) even apply to me. If anyone has any suspicions on why this could be happening I would appreciate it, thanks!
Most likely related to control schemes I would guess
how do i go about debugging that?
Are you using control schemes?
yes
Is there a good reason for using control schemes? Mostly those are useful mainly for local multiplayer
They end up causing people issues like this a lot
I have them for different devices like I thought you were supposed to?
all of those were there when i hit create actions though
It's only needed for local multiplayer where you need the system to be able to identify different people by different devices
what may be happening is your input is getting bound to the first device it sees - which is maybe not the one you're actually using
so does onControlsChanged not change the control scheme?
wow i was under the assumption that they are for different devices schemes not different PHYSICAL device schemes
so I should just remove them all and have one called main or something?
also dont think that approach will work, considering im displaying control hints so I kind of need to know which control scheme is active
https://forum.unity.com/threads/multiple-control-schemes-or-actions.727583/
Heres a forum thread i found somewhat helpful, although im not sure what to do considering i DO need to seperate the logic, but i ALSO need them to be able to be swapped and used on the same machine. Not sure how to go about this.
I use them so that I can show proper button prompts.
I'd suggest adding some debug code that shows you which control scheme is active and what devices are detected
just slap that in an OnGUI method or something
I don't know if there's a nicer way to do that in a build
I've set a newly created Input Manager, but I can't swap back.. why is that? ^^'
set a newly created input manager
? What does that mean?
And what do you mean swap?
Is this about the new input system, or the old input manager class?
I pressed "Assign as the Project-wide Input Actions
and swap meaning, I wanna go back to what I had before
Ah, in player settings you can switch the active input system
Project settings > player
If I remember correctly
Hopefully I am understanding correctly
In that top image, open "other settings"
nothin
It is right there in the top image
"Active input handling"
It is currently set to "Both", so you can use the old input as well as new currently
Eh yeah but thats fine no?
Yeah, totally fine
I wanna replace this Input Action Asset:
with this:
Maybe thats the proper wording
Oh, that is a completely different issue
Generate the c# object for that asset
You could delete the other asset if you want too
Got that
I pref not to 😄
what next? ^^'
Still can't press "Assign as the Project-wide Input Actions"
omg.. nvm..
I got it.. it was because Ive been in play-mode, yikes my bad! 😄
Tyvm all 
I have an InputAction with 10 keys, which I'm using for accessing the hotbar items. Works fine.
But I just finished a feature to change keybinds and I want to support control/alt/shift modifiers as well. Changing the keybinds works fine. I also have composite paths such as "/Keyboard/leftAlt + /Keyboard/q" as bindings.
However, now I noticed I can't actually use these bindings at all for my action...
I have UseHotbar(InputAction.CallbackContext context) that gets the event, but context seems to know nothing about composite keybinds. context.action is just straight out missing these bindings.
Any tips on how I could make this work?
The typical approach for a hotbar is just to use 10 input actions
It greatly simplifies rebinding etc
but you still have the events triggered the same way with InputAction.CallbackContext
everything else works, I just need to figure out how to get control+key binding from that context
but I think I just figured it out as well, context doesn't have binding directly, but it does exist in context.action.bindings
Sure I'm just letting you know this is a rabbit hole I've gone down many times and always found multiple actions to be better.
The tiny amount of work to set up 10 actions is way less than all the hoops you have to jump through to handle it with binding disambiguation.
yeah, thanks
spent way longer on it than expected yesterday 😄
Okay I just did this, I basically just did a LogError every frame and printed the control scheme, in the editor it is correct, when I switch to my gamepad it prints Gamepad, and when i switch to my keyboard/mouse it prints Keyboard&Mouse like it should. Then on the build it just continuously prints Keyboard&Mouse even if I am using the controller
as for the devices: it shows all the correct devices in the editor, and then in the build the controller is not listed in the connected devices. so for some reason it just is not even seeing the controller as connected
Update: I think it has something to do with steamworks.net...
for some reason whenever I close steam and get this error (which happens because steam isnt open) THEN and ONLY THEN my controller gets picked up. It is so weird that my input doesnt get picked up when the SteamAPI_Init() succeeds but it does when it fails. Does anyone have information on this?
I found this:
https://github.com/rlabrecque/Steamworks.NET/issues/380
this definitely seems to be my issue, however I am not quite sure how I can fix this yet
EDIT: like it says in that issue forum, I can fix this by opening the steam overlay (in the build) and going to controller settings and when I apply the template for just "gamepad" and close the overlay THEN my input gets picked up. Very VERY weird bug with steamworks, I have read that when you upload to steam and play through steam it should all be working so I am going to ignore the bug for now (as I don't have a steam page / appid just yet) just putting this here in case anyone has a similar issue
EDIT 2: a temporary fix for this is changing the appid in the build folder to anything else besides 480 (i used 12345). What this does is it doesn't load the spacewar controller configuration which is whats rebinding inputs and what-not. However you can't test any spacewar related stuff obviously like achievements (in the build) if you do this
sorry for spam again 
Hey all - I'm trying to have functionality so that when holding right click, the cursor disappears (easy enough to do), but then if you move the mouse while holding right click and release right click, the cursor appears in the same location as where it was when you held right click before moving the mouse. This is similar to games like WoW. I am able to show/ hide cursor, and I have tried a couple of methods where it does place the cursor back to where it was first held, however there is a noticable lag when it reappears and I'm wondering how people handle this - what is the fastest most efficient way to do this so that there is no lag?
Thanks in advance for any pointers
Read the part about cursor warping:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/Mouse.html
I'm implementing a HID wheel whose layout starts with a float for the steering angle.
struct HIDData
{
float fSteeringWheelAngle = NAN;//返回角度
int16_t steeringWheelAxle = 0x8001;
...
I am replicating this HID as part of an InputDevice:
[StructLayout(LayoutKind.Sequential)]
public struct GudsenMozaR9BaseInputReport : IInputStateTypeInfo
{
public FourCC format => new FourCC('H', 'I', 'D');
[InputControl(name = "fSteeringWheelAngle", layout = "Axis")]
public float fSteeringWheelAngle;
[InputControl(name = "steeringWheelAxle", layout = "Axis")]
public short steeringWheelAxle;
...
The value shows up correctly in https://hardwaretester.com/gamepad on axis 0: -1 when at the left limit, and 1 at the right limit. In the Input Debugger, I can see there is a value that changes as I turn the wheel. However, as the wheel passes the centre position the value jumps. It's awkward to explain so I've made a diagram showing the behaviour. On the left is the behaviour on the linked gamepad tester page, and the behaviour I want. On the right is the behaviour I am seeing in the Input Debugger. What could cause this wrapping behaviour?
Displays info about all gamepads connected to your computer. Check buttons, joystick axes, drift, and more. Works with all controllers and joysticks in a modern browser.
you can adjust this by doing inputValue = (inputValue + .5f) % 1f;
Where can I modify the input value like that?
not sure why that's happening though
I would rather solve this problem at the InputDevice level because I have a number of other devices to consider and don't want to change their implementations or have to consider this wheel a special case.
Well do you have your own InputDevice class as per https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/manual/HID.html#custom-device-workflow-example-2---create-your-own-inputdevice-class ?
Yes, is there a way to process input in that class?
I believe by overriding the ReadValueFromXXX methods
not something i've ever done
but maybe you can just do base.ReadValueFromXXX and then try to examine/operate on the resulting data.
Right, I'll give that a go, thanks. void*, my favourite.
I thought the new input system was supposed to make things easier!
I have tried this and ended up only deeper down a rabbit hole of custom InputControls. It seems insane to me that this is an issue at all - why can a web browser handle HID input easily, immediately, with zero setup or configuration while the most popular game engine in the world can't even with hundreds of lines of code configuring it? Would appreciate any support on the above ReadValueFromXXX approach or, ideally, on whatever the correct way to set up the axis in the Input System is.
I've started out this morning by getting a better understanding of the error, and it seems the shape I sketched earlier is not correct, which means any solution that involves scaling the input value is going be be extremely awkward to implement. On the X axis is the correct value, which I'm getting from the gamepad test link I shared earlier. On the Y axis I am plotting the reading from the input debugger. This is a clue, but I'm not sure where it points.
The simultaneous drop and change in gradient suggests to me that the sign bit is being misinterpreted. However, when I tried looking at the raw memory I was disappointed that I couldn't see it change in real time.
I have made some progress on the issue. For whatever reason, the HID layout I was looking at seemed to be wrong: The steering axis is actually a ushort value. However, it needs to be combined with a second ushort value which defines a constant offset which is set using the proprietary software for configuring the hardware. In my current setup, this is interpreted as two axes, but I would like it to just be one. This would be easy to do in 'application' code, but it would mean adding a special case and polluting my player control code with a correction for a specific piece of hardware, so I would again like to solve this at the InputDevice level.
My question is therefore how can I write code to combine these two AxisControls such that the Input Debugger only reports a single value, which is a combination of the two?
[StructLayout(LayoutKind.Explicit)]
public struct GudsenMozaR9BaseInputReport : IInputStateTypeInfo
{
public FourCC format => new FourCC('H', 'I', 'D');
[FieldOffset(0)] public byte reportId;
[InputControl(name = "fSteeringWheelAngle", layout = "Axis")]
[FieldOffset(1)] public ushort fSteeringWheelAngle;
[InputControl(name = "steeringWheelAxle", layout = "Axis")]
[FieldOffset(3)] public ushort steeringWheelAxle;
...
I've managed to create a composite axis based on two axes, one for each side. However, they are configured such that 1 is in the middle and zero is at the peripheries, so I want to apply processors in the InputActions asset to fix this before the values are read. However, they appear to do literally nothing. To test, I added this 'scale' processor, but the output values are identical to without it. What's going on?
They are properly saved in the .inputactions
^ From what I can tell, processors don't work when applied to individual parts of a composite axis. Obviously this behaviour is undocumented, presumably a bug. I've had too many bug reports closed without resolution on me to be bothered filing another, but I believe I have just about found a working configuration so no need to reply to any of the above. Thanks!
Is there any way to stop InputSystem.onAnyButtonPress from propogating the event?
I'm using InputSystem.onAnyButtonPress (using CallOnce), which is all working fine and dandy, and I can apply the correct logic.
However, after it runs the supplied callback, it still sends the event forward to the input system. This makes it so that when I use certain buttons that match an action, that action gets performed (eg Submit on the UI). This is unwanted behaviour, I'd like to handle this event as a one-off thing where I'm doing one-time logic. Is there any way to consume the event/stop it from propogating? While there are hacky workarounds such as disabling UI interactability or disabling the actions, it feels like there really ought to be a way of stopping the event somehow.
I've scoured google/documentation but didn't have any luck, the only thing I could find was a forum post asking the same question, with no replies unfortunately: https://forum.unity.com/threads/consuming-inputevent-with-inputsystem-onanybuttonpressed.1508648/
I'm using the new input system to trigger a popup when the player is in range of an interactable object, and triggers the correct Action. Once the...
Hi. I can't figure out how to prevent multiple callbacks during TouchEnded.
It always fires twice (in some cases three times). Any experiences and remedies to solving this? Thx
They have different phases, no?
They do have different phases, but that's not the issue. TouchPhase.Ended propagates twice, like i said originally
or three times even
it's due onBeforeUpdate and onUpdate and onAfterUpdate (input system internal code)
however, if I touch, wait for 0.1s and then release, then it propagates correctly.
but i can't rely on this behaviour
Quite honestly, I have no idea where to post this. When moving the camera horizontally, it randomly speeds up when looking in the positive z direction. And it only does that at a specific point in the map
I have checked and confirmed that it is not an optical illusion, I am extremely confused and at the end of my capabilites. That bug is dark witch craft
Code?
yeah one sec
using System.Collections.Generic;
using UnityEngine;
public class PlayerLook : MonoBehaviour
{
public Camera cam;
private float xRotation = 0f;
public float xSensitivity = 30f;
public float ySensitivity = 30f;
public void ProcessLook(Vector2 input)
{
float mouseX = input.x;
float mouseY = input.y;
xRotation -=(mouseY*Time.deltaTime)* ySensitivity;
xRotation = Mathf.Clamp(xRotation,-80f, 80f);
cam.transform.localRotation = Quaternion.Euler(xRotation, 0,0);
transform.Rotate(Vector3.up*(mouseX*Time.deltaTime)*xSensitivity);
}
}```
You should not be multiplying deltaTime into your mouse input
That's your main issue
Also !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Interesting, thanks I will try that tomorrow. I had copied that code from a yt tutorial quite a long time ago
Many YouTube tutorials get that wrong, famously including the Brackeys one
That might be why 
Cool cat btw.
bumping
I have changed line 18 to: xRotation -=mouseY * ySensitivity;
The camera is ridicolusly fast now, I think that Time.deltaTime is required
also additionally, even if Time.deltaTime was the issue, wouldn't that issue exist all the time and everywhere in the game?
Checking with the stats tab it shows that the place where my mouse is accelerated I have around 180 fps. Everywhere else I have around 400-500
You need to just compensate by reducing the sensitivity value
you absolutely do NOT want deltaTime
If your framerate is relatively stable it won't be noticeable. This is why it happens only in a single place, because when you look in that place your framerate is either dipping or increasing by a lot
Again, get rid of deltaTime, and adjust your sensitivity down to compensate
yes exactly, as I was saying, it's related to your framerate changing
if your normal framerate is around 4-500 you will need to reduce your sensitivity value by about a factor of 400 or 500 to compensate when removing deltaTime.
E.g. if your sensitivity was previously 400, it should now be 1.
(which is a much more sensible value anyway)
yeah will try, thanks in advance
That seems to have done the trick
although I have to set my sensitivity to 0.05 for it to be playable
Do you have a very high dpi mouse perchance?
yeah but I tried all different settings for it and it didn't make much of a difference
I used my standard of 2400 DPI, but also the highest of 25600 DPI
2400 dpi is very high and 25600 is extremely high lol.
A standard DPI is like 800?
anybody know why these occur? I am not sure how to debug this
Look at the full stack trace of the error
help, for some reason my input system refuses to work
at first it was working just fine, until I added the event system
now it stops working and only starts to work again when I reload the scene several times
even when I remove the input system again it does not fix it,
there are two player inputs, does this have something to do with it?
You should only have one PlayerInput
unless you have multiple players
each one monopolizes a set of devices
saw only now, already solved, gonna create a main input manager for later uses
According to this code you're not even using the PlayerInput component
Seems like you should have 0
soo... I was thinking the same thing... its quite a picle isn't?
everytime i deleted the player input
it stops working
You'd have to define what "it" is
If you mean this code it's because you never did _playerInput.Enable();
the input
this do not work without the playerinput, so I think is required for some part of the code, I was not the guy responsible for that part, just trying to salvage as fast as I can
but later I shall see how to better organize this
I am looking at it but theres not a single one of my scripts in it so I have no clue what caused it:
That looks pretty bad lol. An assertion with the message "should not get here" means something is going wrong in a way the Unity devs didn't expect. I would try:
Updating/upgrading the input system package if possible. Followed by perhaps recreating my input actions asset.
What kind of setup are you using?
yeah when I saw that I was like welp im doing something terrible
I think I sort of narrowed it down essentially I was holding down a button and then the scene switches and that error happens whenever I press that bind again
my hunch is it has something to do with event subscriptions but I am unsubscribing from everything I can find...
with the new input system is there a way to find the KeyControl on the current keyboard via a string input? For example I want to store "aKey" as a reference, and then determine if Keyboard.current.aKey is pressed, where aKey may be a different value
is there a known bug for the Processor Editor stuff in the unity 6 preview?
I copied and pasted the exact stuff from the docs to sanity check since my vector3 one doesn't display the field and I can't get any version to properly display unless it's a primitive type WITHOUT a custom editor
the scale and invert ones are built in to the package but they work 
There's the Key enum
Yeah i ended up using that thanks
This has nothing to do with the input system as far as I can tell
Oh sorry i didn't mean to send that in this channel 😭
(New Input) How do I make a control rebind? I already tried with this, but it gives errors on every single frame:
https://hatebin.com/hchsgaplls
it gives errors on every single frame
Sharing what errors you get would be useful
InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.Input.GetButtonDown (System.String buttonName) (at <37f4ee0fc1934e1aba69cbe63e6dcdcd>:0)
UnityEngine.EventSystems.BaseInput.GetButtonDown (System.String buttonName) (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/InputModules/BaseInput.cs:126)
UnityEngine.EventSystems.StandaloneInputModule.ShouldActivateModule () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/InputModules/StandaloneInputModule.cs:229)
UnityEngine.EventSystems.EventSystem.Update () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:503)
Yeah that has nothing to do with rebinding
I have no idea why it puts so many weird stuff to it.
That's beause you're using the old StandaloneInputModule
Take a peek at your Event System object in the scene
Ok let me retry
Action 'left' not found in the Input Action Asset.
UnityEngine.Debug:LogError (object)
ControlsButtonScript:Start () (at Assets/Scripts/UI/ControlsButtonScript.cs:40)
Even though I have a key that is supposed to point left, that currently being A
Though nothing lets me specify "hey, yea game, THIS is left, please don't be complicated about it"
I already put my player controls script into it
You don't have an action named "left"
The window where I put the keybinds in doesn't have a way to name them, I already tried to see.
that window is not relevant to your problem
(it was relevant to the earlier error)
You need to open your input actions asset
your actions are defined there
most likely you do not want to modify this from what the default was, I recommend restoring it
I'm not sure which one you mean
Done
the one on the right, yes
you have configured it... completely incorrectly
I did it like the tutorial did, I added the keys and the binds
If a tutorial told you to do that, you should throw it away and find a different tutorial
This is a more typical setup example:
you define actions
and bindings for each action
Since you don't currently have an action named "left" your code that tries to find such an action of course fails
Okay I'll try that
Notice how the action name is gameplay relatd
Thanks, I will test it now.
In this part, I get sent Action 'left' not found in action 'left'.
void Start()
{
if (buttonImages == null)
{
Debug.Log("No images in buttonImages!");
}
if (isUp) { actionName = "jump"; }
else if (isLeft) { actionName = "left"; }
else if (isRight) { actionName = "right"; }
else if (isRun) { actionName = "run"; }
else if (isShoot) { actionName = "shoot"; }
// Find the action from the Input Action Asset
action = inputActionAsset.FindAction(actionName);
if (action == null)
{
Debug.LogError($"Action '{actionName}' not found in the Input Action Asset.");
return;
}
// Enable the action
action.Enable();
}
Did you create an action named "left"?
Yes
can you show a screenshot of that?
ok and now the inspector for your script?
This one?
this script
Well, the one attached to the gameobject..
I have a bit of a strange question. I'm FINALLY starting to get into the new input system. Been using a combination of InControl and the old system for years. The thing is, I want to know what is the best way to know if an element/item is being hovered over? In the old days it was OnMouseXXX(). What is used now?
Nothing to do with the input system - but you would use the event system for this
IPointerEnterHandler/IPointerExitHandler
or the EventTrigger component
This one?
yes
ok so now - can you show the exact error you're getting with this?
That's what I've been doing, but that seems like an old system that is getting more use now? Does this work for touch as well?
yes it works for touch
that's the short answer at least
the long answer is it works with whatever you set up in the input module
the defaults are usually good enough
NullReferenceException: Object reference not set to an instance of an object
ControlsButtonScript.Start () (at Assets/Scripts/UI/ControlsButtonScript.cs:46)
ok that's a totally different error
Okay. Good to know. I assume that this can be turned off if controller input is the main way to do things, like for consoles and such?
likely because you didn't assign Player Control here in the inspector
Okay. I think I have to make it a script though, because I don't have a player in the scene. It's the Main Menu.
well I don't know anything about what this script is doing honestly
When the player clicks the rebind button, it should wait for the player to input a key, then it should rebind, for example, the left key to be j instead of a if the player pressed j.
sure but I havce no idea why it wants to reference the "Player Control" thing
or what it's doing with it
I copy pasted it from somewhere because I have no idea how to do it.
Should I just start this script from scratch?
Does anyone know how I make this button component call a void function from a script in the MainMenu object? Should it even be in "Target"?
You need to start by setting your inspector back to normal mode. It's in debug mode right now
Also this is a #📲┃ui-ux question, not the input system
Ooooh that's why it look weird
my bad, but thank you!!
thanks
How can I make a weapon switching with the new input system
I want to make it using mouse scroll
What do you have so far?
I have made 2 weapons just some cylinders for testing purposes. Ill send the script.
following this tutorial https://www.youtube.com/watch?v=kasbsBho9ZM&list=PLwexm95o5iz5GOp_7v91j1Uk-SDAbe3el&index=7
In this video I built on top of the last one and continue working on the weapon system by adding weapon switching.
PROJECT LINK: https://github.com/Plai-Dev/weapon-system/
Like & Subscribe!
Timestamps
00:00 Intro
00:03 Changing Shoot Point
00:34 Adding More Weapons
01:15 Weapon Switching
03:27 Preventing Bugs
04:10 Outro
Socials:
Discord: h...
Never Mind I figured it out
Hey I'm subscribing to InputSystem.onDeviceChange manually myself to detect new devices being added to then create InputUsers by doing InputUser.PerformPairingWithDevice myself, but its not quite working as I expected after entering Play Mode, as the keyboard does not get detected and the controller just gets detected when first plugged in
I mean, I guess it is working as intended, because the keyboard does not change as its already plugged in, and neither does the controller after its initial connection
But I don't know how I should do it instead
public static class DeviceUtilities
{
private static SystemDefaultActions inputActions = new SystemDefaultActions();
public static void EnableJoining()
{
Debug.Log("Joining enabled");
InputSystem.onDeviceChange += DefaultOnDeviceChange;
}
public static void DisableJoining()
{
Debug.Log("Joining disabled");
InputSystem.onDeviceChange -= DefaultOnDeviceChange;
if (inputActions.System.enabled)
{
inputActions.System.Disable();
}
}
public static void DefaultOnDeviceChange(InputDevice device, InputDeviceChange change)
{
Debug.Log($"Device change detected: {device.displayName} - {change}");
if (change == InputDeviceChange.Added)
{
// Listen for actions from the new device
var actionMap = inputActions.System;
if (!actionMap.enabled)
{
actionMap.Enable();
}
// Register the action callback, this should be pressing L+R in a controller or Space in a keyboard
actionMap.UserJoin.performed += context => DefaultCreateNewUser(device, context);
}
}
public static void DefaultCreateNewUser(InputDevice device, InputAction.CallbackContext context)
{
if (context.control.device == device)
{
InputUser user = InputUser.PerformPairingWithDevice(device);
Debug.LogWarning($"Device {device} paired with user {user.index}");
// Unsubscribe from the action callback
var actionMap = inputActions.System;
actionMap.UserJoin.performed -= context => DefaultCreateNewUser(device, context);
// Disable the action map
actionMap.Disable();
}
}
}
Basically the idea is that you can add as many devices as you want but unless the game allows you to join and you do the join action you aren't registered in the game
plus some other stuff i have around, but thats after joining
(this is also supposed to support multiplayer, in case anybody sees im doing something wrong)
Why not just use PlayerInputManager/ PlayerInput which does all this for you
I'm using DOTS
I used it previously and I ended up writing my own variation of player input manager and i just scrapped all of it as there were some issues with device and user pairing (i wasnt able to use both a controller and the keyboard to move my character, where i could before by using PlayerInputManager)
And I extremely simplified it to the bare minimums, which as of now its just that
still feels like re-inventing the wheel. I believe the PlayerInputManager solution is already pretty light-weight, so just because you're not using absolutely all of it's features doesn't mean you should implement your own, most likely worse, solution to input
I still would rather do it manually
I just need the InputUser which I then shove into a component in an entity, which I would then do whatever I want with systems
Hello, I'm trying to understand the 1D axis of the input system, I've set it up like this:
It's all working fine except it never goes back to 0, is that expected behavior?
Wdym by it not going back to 0? Sounds more like a code issue on your part
Probably you're subscribing only to the performed event and not canceled for example
SO let's say I press Q it return -1 but when I release it it's still returning -1
Again, you'd have to show your code
How is the new input system usually managed, do you put all inputs into 1 class?
What do you mean by "putting inputs into a class"?
there isn't really a "usual" by the way, the system can and is used in many different ways by many different games
Like have 1 class that stores all the values which other gameobjects can read
No that doesn't seem like a great approach
That sounds like adding an unecessary middleman
But it really depends on your game and your circumstances
Coming from web dev, it's normal to have 1 class that has it's purpose to not mix all stuff together
I use that but to read input from it I have to pass it many places to make it work with my state system
how is that different from passing your proposed class to many places?
To avoid using many different names and know that the name means it has something to do with input
No idea what you mean by that
it's more that when I modify something I have to back paddle a lot to fix it
and it get's more confusing as the project grows
So I normally would solve it by making classes for each purpose. Like bulletphysics class, input manager, state manager etc. As I'm fairly new in game dev the approach might be different.
I'm still not sure what you mean. Could you give an example?
What kind of change would you make and what backpedalling would result?
For example, I want to disable all inputs with a single function, or I want to add a new input that can modify another input and have it apply to five other states. I want to avoid to go into the 5 other states to add that functionality
A simple wrapper around the actions asset can do all of that
There's no good reason to duplicate the action values.
If you want to disable inputs, I'd consider swapping to an Action Map that has only some / no Actions
https://christopherhilton88.medium.com/how-to-swap-action-maps-in-unitys-new-input-system-22f68079a5a9
For modifying inputs with other inputs you have Modifiers
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/ActionBindings.html#two-modifiers
Hi I recently start learning and I want to disable movement related action maps on first scene but I can't do that what am I doing wrong
Does everyone use the new Input system? Because reading the limitations it seems to still have issues - UGUI not consuming key presses, Monobehaviour mouse methods not supported etc.
MonoBehaviour mouse methods are obsolete. Use the event system
But no, not everyone uses the new input system
sorry, i'm been busy with work but I'm been working on this again and I'm still unable to find a solution
I guess I should look again into the input player manager, after all I did get that modified version off it before even if was janky
something im doing wrong with that new code when compared to that
I made two keyboard control schemes - "Default" and "Pro". Im trying to use PlayerInput.SwitchCurrentControlScheme to swap between them, but no matter what I do it seems like both schemes are active at the same time. Am i misunderstanding what control schemes are? I want two differnet layouts the player can swap between.
Probably a hardware issue
your keyboard doesn't support that key combination
You can test it here https://www.mechanical-keyboard.org/key-rollover-test/
The term key rollover refers to the number of keys that can be simultaneously registered by a keyboard. The following online key rollover test makes it easy for you to verify specifications from manufacturers. You can try out various key combinations and test how many keys your keyboard can handle at once.
First, you need to change the action type and control type, then you can add composites
It would be great if Unity simplified this input system starting with Unity 6 and discontinued the input manager. It's annoying having to manage 500 packages just to create the inputs
at least for me it took almost 3 days
What packages other than the InputSystem package are you talking about?
when i got to make a game like mine, it got cinemachine, input system, probuilder, 2D sprite, sprite editor, like damn, i guess it could be lighter yk?
it would be pretty cool if unity make an update only to optimize the storage size of the packages and remove (or hide) some legacy stuff
when i first started at unity (coming from game maker 2) i looked at the open editor, took a deep breath and thought: "there's too much stuff, im really screwed"
eh, there's a similar vibe when opening Photoshop or any other powerful software tool. You don't need to learn everything at once.
For real
Oh, I guess I was confused, think you were saying you needed a bunch of packages for the input system.
But yeah, having it modularly available is a really good thing imo. Remove what you don't need, add what you do, have as small a program as possible
@timid dagger nah
still
doesn't work
i cant see 2dvector
oh i see
is that up left down?
lmao
Yep. It lets you assign each axis however you want.
can you come dm?
i have a some questions
You can post your questions here.
its about codes you can't
so it is against the rules
Btw, after selecting Control Type as Vector2 you will also be able to select sticks/d-pads in regular bindings.
Ok then, dm me.
im facing an issue where if I touch twice quickly, the second touch does not get registered.
void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
Debug.Log("Start. touch state: " + touch.phase);
}
else
{
if (touch.phase != TouchPhase.Stationary){
Debug.Log("Update. touch state: " + touch.phase);
}
}
}
}
The console log is like this. The bracket being the action im taking
(screen touched)
Start. touch state: Begin
(touch release, and touch again quickly)
Update. touch state: Ended
any ideas how I can solve this?
Guys i found a bug in input system, and i need help to fix it.
So if you using Button action, and you press this button then while pressing that button you do alt+tab, it will no more be pressed, but release trigger also not called.
What can i do to fix it?
Probably a stupid walk-around, but you can try creating some release trigger equivalent and call it for all no longer held inputs whenever OnApplicationFocus is called.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationFocus.html
Not sure if it will work though, it's just an idea. It would be better if they fixed it though, because it seems like a bug that could affect many games.
That's not really a bug in the input system, it's how the Windows operating system handles input. It only sends input events to the currently focused application unless you ask for special permissions
But yeah using OnApplicationFocus is the workaround
Thanks guys for help!
Hello,
I am working on a weapon system, now in the new inputs system, there isn't a "GetKey" , "GetKeyDown"
so I am using a performed and canceld events to check, is this the right way ?
It wasn't a stupid walk-around, but actually a solution btw. :)
I'm not pro, but i'm using IsPressed(), WasPressedThisFrame(), WasReleasedThisFrame() for holding and releasing button
Ok, but have you got any idea about how to check like if he still pressing or not?
cuz I want to check if the gun can shot with one click it will trigger the shot void, but if he can't he will trigger it one time.
IsPressed() to check if still pressing.
WasPressedThisFrame() will be true only first frame of pressing
WasReleasedThisFrame() will be true only first frame when releasing button
When i say first frame, i mean only 1 frame
so it's gonna aply just one time?
Only for WasPressedThisFrame() and WasReleasedThisFrame() it's like GetKeyDown, GetKeyUp
And IsPressed() is for GetKey
Ok, Thanks for that
anyone have any idea why the Sector interaction from the XRToolkit doesn't play nice? Won't let me configure it. Unity 6000.0.5f1
when it's something it doesn't like, it does at least stipulate that, but when it's supposed to work it doesn't. if that makes sense.
Maybe a #🥽┃virtual-reality question.
Good point, I'll leave a link there 🙏
Hello! I have two characters in my 2D scene and two input maps. As it stands now, I also have two seperate scripts, for movement. I'd like to make one script that has a slot to assign an input map, just to streamline things. I've tried to achieve as such by doing what I did below -
public InputActionAsset _fieldControls;
private void Awake() {
_fieldControls = new InputActionAsset();
...
_moveAction = _fieldControls.Player.Move;
which does result in getting the option to choose the input map when attaching the script to an object like shown.
However, it results in the compiler error, also attached to this as an image. How can I fix it so that I can assign an input map to the script outside of the .cs file but still have that script work with that map?
https://gdl.space/zadixikeci.cpp this might help you with your stuff
and this is the config for it
What is this? I'm still new to Unity so it's hard to really read through and understand a script like that without more context of what it is/does
basically once i spawn a new player i attach the InputController to it which loads the default input map and binds it to the device that triggered the new player creation (keyboard + mouse, controler 1, controler 2) etc
if you instead change the map instead of the bound device you can bind a different map to each player
Why are you doing new InputActionAsset()
Presumably you want to instantiate your generated C# class. Not InputActionAsset
I see. I will try to figure out how to do that. Thank you!
I mean it's as simple as using WhateverYourGeneratedClassIs not InputActionAsset
use the correct type in your code
anyone ever use the input system with nintendo switch joycons? simply cannot get right stick to work
Right now I don't believe you can get the joycons working on the Input System. you can get the pro controller working easily, and I have integrated that myself into my own open-source stuff, but the Joycons use proprietary connectors. Someone I knew in uni who tried to get joycons to work couldn't really get them hooked up to USB either
Whatever nintendo's doing with the joycons, it seems intentionally proprietary and most stuff is easily buggy around them
I'm working on migrating a project from the legacy input to the new input system, is there a way I can easily map something like "Joystick Button 10" to a specific button on a gamepad??
I need the equivalents of JoystickButton N to gamepad button, this is because the game uses an alternative controller for inputs so the specific buttons are very important to keep the same
You create actions and bind controls to them in the input actions asset
I don't have access to the layout/mapping of Alternative controller input to gamepad input
I know
I'm just trying to figure out what would be "JoystickButton8" for example to its corresponding generic gamepad button
I'm not sure I understand to be honest. You don't map buttons to other buttons, you map buttons to actions
Hckskgkdkg ok lemme try to explain it better
Gonna log in on PC for screenshots n stuff
things are worse than i thought, but basically the game currently uses the KeyCode system and the Input.GetKeyDown methods.
In this picture, Element 0 is set to JoystickButton10, and Element1 is set to JoystickButton8
Since KeyCodes are not something that properly exists in InputSystem, i need to basically map the "Equivalent" gamepad button to it.
Ergo, how could i know which "Gamepad" button is "equal" to JoystickButton8, for example.
Hi everyone! This is my first post on the Unity Discord, so I'm hoping I'm putting it in the right place. My company AccessVR has a Unity-based VR app that we use to distribute training content. We recently decided to port the app from VR to the iPad. I am doing all of this work myself. At the moment, I have a working version of the app, but the implementation feels fragile. I was hoping that we could find a way to map Touchscreen input actions through the XR Interaction Toolkit—this way, all of the interactivity in our experiences could be implemented once, and consistently, no matter whether the experience is playing through a HMD (like Quest) or on a tablet (like iPad). Happily, this sort of works, but only if the UI elements are fixed to the Camera's Z axis. It's as if the raycasts for the touchscreen events are always being drawn to some point that is really close to the camera instead of to a point that is predicted to be on the other side of the UI, allowing the ray to intersect... well... anything. Additionally, putting the UI Canvas into Screen Space, which is ideal for 2D platforms like the iPad, means they don't receive the input actions at all, even if the UI is fixed to the Z axis. Bottom line: if I put some UI out in Worldspace in a way that is not fixed to Camera Z axis, the touch screen input coordinates don't land where they should. I can work around this by adding some manual raycasting to every UI element, using Touchscreen input actions to trigger the drawing of rays, but this really defeats the purpose and simplicity of the XR Interaction Toolkit. And not being about to use Screen Space means I can't take advantage of things like dynamically resizing canvas (without coding the resize events myself). Has anyone tried anything like this before? Is there a technique I'm missing? It feels like this should work, if only I knew what I don't know I don't know 🙂
is there a way to detect whitespace characters using Keyboard.current.onTextInput in WebGL builds? From my testing it properly invokes with standard letters but fails to detect backspace, esc, arrows and other similar whitespace chars.
~~Edit: Found a solution, but it needs to individually check non-printable characters:
cs
private void OnEnable()
{
Keyboard.current.onTextInput += OnKeyInput;
}
private void OnKeyInput(char key)
{
if (Keyboard.current.backspaceKey.wasPressedThisFrame)
Debug.Log("Backspace pressed!");
}~~
(doesnt work I was mistaken)
I'd recommend using a Screen space UI for iPad.
As for input working or not that will of course just depend on your event system, input modules, and raycasters
I thank you for your response—in the very least, it makes me feel like the way I'm describing our challenge makes sense. I think the thing I'm working to eliminate is using XR Interaction Toolkit to support both XR input bindings (like XR Controller/trigger) and Touchscreen input bindings (like Touchscreen/Press). What I have that is almost 100% functional is doing exactly this: we have a custom Action Map with a custom Action called "LeftClick_RightHand" (a weird name, I know, inherited from a much older version of the software), and it is triggered by the RightHand XR Controller/trigger binding as well as the Touchscreen/Press binding. That action is assigned to the UI Press Action input property of the XR Controller (Action-based) component on the RightHand Controller game object in our XR Player Character prefab. Through all of the prewired elements of the XR Interaction Toolkit, this means that pulling the trigger on an XR Controller and touching the screen of the iPad both have the same end result: the XR Ray Interactor casts a ray, the first element that gets touched is the thing being interacted with, and in the case of UI Canvas, the element receives a click. This works without any specific wiring on the UI elements: I don't have to tell a Button that it is specifically receiving "LeftClick_RightHand" action events, because the UI element is (I think) treated like an interactable, and so the XR Interaction Framework triggers it automatically. So again, I think where this all falls down is that the touchscreen events don't seem to have have Z axis rotation data—and the XR Controller trigger events don't either, but in the case of the XR Controller, the angle of the origin for the ray is set by whatever the transform rotation of the controller game object is at the time the trigger action fires. I just don't understand how to achieve the same thing in the touchscreen context without a custom raycaster—custom raycasting works, but then I have to...
...setup every UI element manually, instead of relying on the automatic "wiring" that the XR Interaction Framework does so elegantly.
One thing that I have just determined beyond a doubt is the limit in XR Interaction Framework for using Canvas in World Space render mode only; from the documentation: "All UI elements exist in the canvas. In the XR Interaction Toolkit, a user can only interact with canvases that have their Render Mode set to World Space. (https://docs.unity3d.com/Packages/com.unity.xr.interaction.toolkit@3.0/manual/ui-setup.html)"
I should note too that I am using AR Foundation here for the iPad app so that the user can "look around" in the VR space by rotating the device. And as I'm reading the AR Interaction section of the XR Interaction Framework guide, I think I am realizing that I'm missing a bunch of other built-in components such as the Screen Space Ray Interactor.
I'm trying to use my switch pro controller, but when i press any button it doesnt recognize any, additionally i have generic bindings from "Gamepad", which should cover what im trying to do, but its not working either
the device does indeed get recognized as a switch controller
so I don't understand what is happening
theres absolutely zero events coming through
software that uses SDL input has no issues with my controller (it even reads gyro input, which is what im interested on right now), so its absolutely a Unity thing
turning the controller on and off doesn't do anything, other than unity losing the device and bringing it back
I'm going through the server's chat history and it seems other users had this issue years ago, but they were all unanswered
This is Unity 6, by the way
What version of input system do you have installed?
I have a xbox controller and it works just fine
then there's obviously keyboard and mouse, which also do work fine and the actions i have do work fine
1.8.2
For whatever reason now its sending one trillion events every second, this seems to line up with what some users say, but at least the buttons and mappings work now.
All I did was head to Steam and enable / disable their switch pro controller compatibility thing
Oh nevermind, its actually reasonable for it to send six million events, its probably the gyroscope
I do need to have steam running in the background for it to start sending data for some reason?
Actually enabling / disabling Steam Input for Switch Pro controllers on Steam just seems to have wake it up as it doesn't matter if its enabled / disabled it behaves the same
its just that enabling it "woke" it up?
Anyways, gyro, is there a way to get it working? I tried binding it to "tilt" in many different bindings yet none works
only the right stick one is getting recognized
Are you using the steam controler thingy?
unity should be able to recognize the controler without steam acting as a connector
Which Steam Controller thingy? Is there something else than just activating steam input support for the pro controller?
I actually closed steam so its not running in the background and turning on / off the controller makes it no longer function in Unity
It just doesnt send any data
Actually, just opened Yuzu, and just doing that "woke" the controller up and its sending data again
Yuzu uses SDL, which is what I assume Steam uses internally as well (as it had Valve employees do commits to its repository regarding controllers)
closing Yuzu makes the controller stop sending data
So there's something that SDL applications do that tells (?) the controller to send data or not (????????????????)
And thats something that Unity (nor HTML5 Gamepad API, I'm testing with this website which I found on the Unity Forums https://hardwaretester.com/gamepad ) doesn't do
Displays info about all gamepads connected to your computer. Check buttons, joystick axes, drift, and more. Works with all controllers and joysticks in a modern browser.
I just launched Zenless Zone Zero which uses Unity and the same thing happened, the game didn't recognize my controller until I opened Yuzu
man.... what the hell..
This is all wireless, by the way
Thought I should mention it considering that most other users that also had this issue in the past said that wireless kinda sucks
Unity should be able to detect the pro controller natively without steams assist
That is obviously not being the case, however
I can try wired in a bit
But third party software here is actually assisting it to work, otherwise it just doesnt work
(I just had Steam)
I just added a friend as a collaborator and his inputs are not causing the character to move when it can work fine on my project. Is there a common issue that can cause this?
His project has the Input System package included, the scripts are all identical, etc. (he downloaded it straight from our repository)
Cant seem to be able to test it wired because it just gets forced to run as XInput
SwitchProControllerHID has no members holding data for gyro, though
I tried creating a Vector3 action and binding it to gyroscope and accelerometer paths, and it did absolutely nothing
Also the device is not considered noisy
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/api/UnityEngine.InputSystem.InputControl.html#UnityEngine_InputSystem_InputControl_noisy
Okay I have the gyro and accelormeter sending data to the debug window, but i have no idea what's the control usage string (https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/manual/Controls.html#control-usages) for the "gyroscope" and "accelerometer" actions
You know, so it automatically gets wired up with that default gyroscope and accelerometer bindings that the input system offers
public const string SwitchProControllerGyro = @"{
""name"": ""SwitchProControllerHIDSensor"",
""extend"": ""SwitchProControllerHID"",
""controls"": [
{
""name"":""accelerometer"", ""displayName"": ""Accelerometer"", ""format"":""VC3S"", ""offset"":19,
""layout"":""Vector3"", ""processors"":""ScaleVector3(x=-1,y=-1,z=1)"",
""usage"": ""<Accelerometer>/acceleration"",
""noisy"": true
},
{""name"":""accelerometer/x"", ""format"":""SHRT"", ""offset"":0 },
{""name"":""accelerometer/y"", ""format"":""SHRT"", ""offset"":2 },
{""name"":""accelerometer/z"", ""format"":""SHRT"", ""offset"":4 },
{
""name"":""gyroscope"", ""displayName"": ""Gyroscope"", ""shortDisplayName"": ""Gyro"", ""format"":""VC3S"", ""offset"":13,
""layout"":""Vector3"", ""processors"":""ScaleVector3(x=-1,y=-1,z=1)"",
""usage"": ""<Gyroscope>/angularVelocity"",
""noisy"": true
},
{""name"":""gyroscope/x"", ""format"":""SHRT"", ""offset"":0 },
{""name"":""gyroscope/y"", ""format"":""SHRT"", ""offset"":2 },
{""name"":""gyroscope/z"", ""format"":""SHRT"", ""offset"":4 }
]}";
this is what I have right now, usage just doesn't work
Okay i got it to work, just had to add it to the action
So as a breakdown, that layout there exposes gyroscope and accelerometer data, that can be used as a layout override with InputSystem.RegisterLayoutOverride(LayoutJson);
I managed to figure this out thanks to a Unity Japan video https://www.youtube.com/watch?v=D66gfvktrnM which has example code in a repo in the video description, and actually goes to explain gyro and other stuff
最近の FPS, TPS はゲームパッドのジャイロ入力に対応していることがありますよね。これを Unity の Input System を使って実装するにはどうしたらいいんだろう……と思ったので、試しに作ってみました! ジャイロ入力を作ってみたい!と思っていた方はぜひ参考にしてみてください。
サンプルプロジェクト:
https://github.com/keijiro/GyroInputTest
0:00 イントロ
0:38 DualShock 4
1:28 カスタム拡張定義
2:43 動作確認
3:26 簡単なサンプル
4:44 問題点
5:31 問題の解決
7:38 再び動作確認
9:12 まとめ
Also looking through this server's message history, this user had a issue with Filter Noise on current toggled on not working as expected with the Switch Pro Controller. That problem went entirely unanswered at the moment but it happens because the controller by default isn't marked as noisy
More resources to read would be https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/imu_sensor_notes.md , which says things like Internally Switch uses revolutions per second instead of degrees. That's why the gyro calibration is always 13371. which would explain some other issue I've read in the chat history where an user was confused about the data that the controller was giving
I hope this info dump assists anybody that tries to search through the server for help on the Switch Pro Controller, especially about motion controls / gyroscope / accelerometer, though using Discord as info storage isn't the most ideal.
I'm trying to test out my input system on my Android using Unity Remote 5, but it's really glitchy and freezes often. Do you have any advice? I followed the steps here to get it working, and it does play on my Android but it freezes and I need to restart Unity Remote 5 quite often. Here are the steps I followed:
https://stackoverflow.com/questions/65642880/commandinvokationfailure-unity-remote-requirements-check-failed/66345155
I'm using Android 10.0 but I set the minimum to be 9.0 'Pie' and the game does come up on my phone, it just freezes a lot, sometimes immediately.