#🖱️┃input-system
1 messages · Page 29 of 1
hmm, looks really intimidating xd
would you recommend it for every manager in the scene?
no
@austere grottoThank you, however how do I rebind say, the Left binding for Move/Primary/Left?
how do I access that specific binding?
@austere grottoI found a solution, albiet a little hacky.
Apologies if there's a better place to ask this: How do I move my camera in the scene editor as I tweak things without it feeling so chaotic? I feel like I spend more time correcting my position in the editor than I do actually doing the things I want and wanted to see if there were tips!
https://github.com/keijiro/GyroInputTest/blob/main/Assets/GyroInputTester.cs
https://www.youtube.com/watch?v=D66gfvktrnM
最近の FPS, TPS はゲームパッドのジャイロ入力に対応していることがありますよね。これを Unity の Input System を使って実装するにはどうしたらいいんだろう……と思ったので、試しに作ってみました! ジャイロ入力を作ってみたい!と思っていた方はぜひ参考...
Unity Japan has a video about it and a example
I have implemented Nintendo Switch Pro Controller Gyro with this layout override
//https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/imu_sensor_notes.md
//According to that, accelerometers start at 13, and gyro at 19, but from debugging the data that seems switched around?
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)"",
""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)"",
""noisy"": true
},
{""name"":""gyroscope/x"", ""format"":""SHRT"", ""offset"":0 },
{""name"":""gyroscope/y"", ""format"":""SHRT"", ""offset"":2 },
{""name"":""gyroscope/z"", ""format"":""SHRT"", ""offset"":4 }
]}";
Gets registered with ```cs
InputSystem.RegisterLayoutOverride(SwitchProControllerHID_Sensor.SwitchProControllerGyro);
Then I just implemented it directly in a Inputs Action Asset
You do need to figure out the memory layout of the data and the format, you can do that with the Input Debugger
If you are using Windows then maybe its fine...?
I tried connecting one of my wii motes to my linux pc and it just didn't work
If the wiimote works out of the box and is just missing gyro you can use an override, just re-read your message and this quite isn't "own custom device layout" from scratch
but the principles of json is kinda there..? The manual has a section on custom devices
its complicated
A lot of this is debugging the device and knowing your way across the hardware
I'd check github if I were you, additionally check the SDL2 repository since they just implement every controller in existence
i was using the wiimote api but its not working out as welll as id hope
might switch over to vr if i cant make it work :/
ill look into those links tho, ty!!
I'm making a 2D board game, I need to interect with both the UI, and the Grid when the user click outside the UI. I'm starting to learn about UI Toolkit and the new Input System. I'm having hard time understanding what is up to date. I see a lot of tutorials about the new Input System with ImGUI. Is UI Toolkit intended to work with the Input System, or on its own ?
this is really more of a #🧰┃ui-toolkit question.
In UGUI you could get that behavior automatically if you use the Event System for your in-game interactions too.
but UIToolkit has its own event system and I'm not sure how that works
Okay well I wasn't sure which channels it would more fit. But thanks for the anwser
Hey, I'm still new to the new input system, I was wondering how I would make my player move? would I use the Vector2 in the action properties? I'm a bit confused.
Wit hthe way you set things up here you would need to first enable the action:
void OnEnable() {
moveAction.action.Enable();
}
Then in update you can read the value:
void Update() {
Vector2 currentINput = moveAction.action.ReadValue<Vector2>();
}```
the confusing thing is that you have BOTH the PlayerInput component here
AND you have InputActionReferences
I have just showed you how to use InputAcitonReference
with this way you would get rid of your PlayerInput component
You should not be trying to use both
they are two different approaches entirely
If you wish to use PlayerInput with SendMessages as you have, you would instead do this:
Vector2 moveInput;
private void OnMove(InputValue iv)
{
moveInput = iv.ReadValue<Vector2>();
}
void Update() {
// move your character with moveInput here
}```
Pick one or the other
not both
So I don't need the player input component?
I'll just use the inputactionreferences then
Once I read the value Vector2 currentInput = moveAction.action.ReadValue<Vector2>(); would I move the player in OnMove? I want to use AddForce for movement.
Read what I wrote again
OnMove would only be if you are using PlayerInput
I already answered this above
ohhh, so I wouldn't need these then?
So those are for when your using Player Input ↑
Specifically PlayerInput in SendMessages mode
Got you, thanks !
I made some changes and I'm getting errors in handle movement should I store current Input as a variable? private Vector2 currentInput;
this is basic C# at this point
you can't use a local variable you declared in one method in another method
yes you need a member variable here
The issue I'm currently having is when I play my game, I can't click on any of the buttons. It's like pressing on the buttons doesn't do anything.
Important information:
I am using Version Unity 6 (6000.029f1).
I have both input systems enabled
All the buttons have the same IMG & TXT (just different names & images)
How come the text isn’t appearing on the screen? I used input mouse position and camera.main.screentoworldpoint of the mouse position and set the text box position to the screen to world point of the mouse position
I assume the text is a GUI text. You can try using RectTransform utilities to convert the screen position into the local point of the chosen Rect, then set its anchored position accordingly.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html
why does each button have a Canvas component?
You see the white lines in the scene view in the shape of an L? That's the bottom left corner of your screen
You're putting the text outside of the screen
I was watching a video & the dude had a canvas on each. Does each button not need a canvas?
noi
a canvas is a container inside which you are meant to place a lot of ui elements
you just need one canvas at the top level
not sure what tutorial you were watching
either he had some special reason for that or it was just wrong
Ah okay I'll give that a shot later on today, thankyou for your help
Nesting canvases breaks the layout hierarchy and can be very beneficial to performance when you use them to separate static from dynamic parts of the UI or those that update together. If overdone (on every button) it has a negative impact. It’s usually a good idea to have a canvas at the root of each ‘panel’.
its hard to tell but does anyone know why my mouse is jumping around? ill slightly look around and ill just start jumping and stuttering around. my friend said it was a unity engine issue but im not sure
Ahhh thankyou, I didn't know that.
This is the set up, I have removed the canvas on each panel except the Journal_Book (Question would the "root" of the prefab have to have a Canvas instead of the first). I have added the first 2 buttons, (as once I get them working I can just impliment the same thing to the rest.) & also added the code is down below, anything I try & do it doesn't wanna work.
public class JournalCode : MonoBehaviour
{
[Header("UI References")]
public GameObject Journal;
public GameObject[] pages;
public int defaultPage = 0;
private bool isJournalOpen;
private int currentPageIndex;
void Start()
{
foreach (GameObject page in pages)
{
if (page != null) page.SetActive(false);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.J))
{
ToggleJournal();
}
}
public void ToggleJournal()
{
isJournalOpen = !isJournalOpen;
Journal.SetActive(isJournalOpen);
if (isJournalOpen)
{
ShowPage(currentPageIndex);
SetCursorState(false); // Unlock cursor when journal is open
}
}
public void ShowPage(int pageIndex)
{
if (pageIndex < 0 || pageIndex >= pages.Length) return;
// Hide current page
if (currentPageIndex >= 0 && currentPageIndex < pages.Length && pages[currentPageIndex] != null)
{
pages[currentPageIndex].SetActive(false);
}
// Show new page
pages[pageIndex].SetActive(true);
currentPageIndex = pageIndex;
}
// Call this from other UI scripts (e.g., Host screen)
public void SetCursorState(bool shouldLock)
{
Cursor.lockState = shouldLock ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !shouldLock;
}
// Debug method
public void DebugLog(string message) => Debug.Log(message);
}```
I really need help I don't why my swipe detection is not work, it's just not give me the swipe end position and it's been over a week since I start trying to add swipe mechanic.
And for a reason when I touch out from game scene it give me the swipe end position
and I did try to subscribe the Onjump and OnJumpPosition to different input phases and didn't work either
looks like i.m not the only one who faces issuses with input system
Most likely an issue in your code
I want to track the active input device (i.e. the input device that's currently used).
I tried to listen to the onControlsChanged event and call this function:
private void OnControlsChanged(PlayerInput input) {
if (input.currentControlScheme == "Gamepad") {
CurrentDevice = DeviceType.Xbox;
} else if (input.currentControlScheme == "Keyboard&Mouse") {
CurrentDevice = DeviceType.KeyboardMouse;
}
}
But there seems to be an issue: Even when only using a controller, the Keyboard&Mouse branch gets also called. In the editor, when clicking OUTSIDE the game view, it works (that it only tracks controller) . but i dont want to click outside of course (in the build it wouldnt work because of lost focus)
Anyone know how to fix that?
I can't find a way to fix this
I tried all the different supposed "solutions" but its always the same - if i dont manually click outside the gameview it triggers a keyboard and mouse input even if i only press buttons on the controller
It's the same with me
When i click outside the gameview it trigger and it gives me the swipe end position
Is this issue with the unity engine him self?
I can't tell. But I've tried the whole day, all possible solutions i can find on the web result in the same issue
I'm stuck over a week in this.....
Is there someone talk about this issue in internet?
Like YouTube??
not specifically. which makes me wonder because it is such a basic thing everyone would want in their game
let me ask it differently, is someone using onControlsChanged to track the current control scheme - and if yes, which version of InputSystem because then i'll try to downgrade
I even downloaded the official sample from the InputSystem In-Game hints. it has the same issue, it flickers between the keyboard and controller hints. (except you click outside the in game view)
I'm done with unity I'm switching to godot
I'm so done with it
I spent the whole day trying to figure out why I can't get swipe end position when I the touch cancel
But it doesn't work no matter what I do
And it gives me the swipe end position when i click the outside the scene
Your code doesn't make a lot of sense to me tbh. The separation of responsibilities between Jump and JumpPosition actions seems weird
Also it's kinda recommended to just use EnhancedTouchSupport directly for touch gesture stuff
rather than input actions
it's possible with input actions but awkward
For doing it with two actions I would basically expect:
- 1 action for the touch/release
- 1 action for the touch position
and you would just read the position action's current value with ReadValue inside the touch/release action callback directly
Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();
It's odd you're doing this and ignoring the callback context^
can someone confirm if this is a bug in the current unity version? i may have to work around this somehow
doesn't matter I did callback too and it's give me the same result
what version of unity and inputsystem are you using?
the new one
and the before it
and I did have this same problem too before year ago when I was trying to get the space release button
Then tell me why in this too videos they do the same thing i did and it work with them but not with me?? https://youtu.be/XUx_QlJpd0M?si=w_Ei3X231Nnrd4Qe
Detect swipes and it's direction with the new input system in Unity 2020. I also show how to add a trail renderer for a cool swipe effect.
ᐅGet the full Source Code Bundle to my Unity Tutorials 🤓
https://sam-yam.itch.io/samyam-full-source-code-to-all-videos
📥 Get the Source Code 📥
https://www.patreon.com/posts/45726030
🔗 Relev...
@austere grotto https://www.youtube.com/shorts/3HNNYWZJRqA
@obscure045
Buy my assets:
https://assetstore.unity.com/publishers/71736
Video Edited On Flixier:
https://flixier.com/
Check It out Its cool.
lmao i just booted up my pc after the horrors yesterday and suddenly it works. 😂 wtf
really?
yes the flickering is just gone suddenly, i didnt change anything since yesterday
guess rebooting did the trick for me, restarting unity did not
well good for you
Me I will continue to....
I don't really know
what should i do
i never tried to make a mobile game, i dont know anything about touch input :/
i think i'm not able to help here
It's ok
I will probably switch to mobile engine
But I don't understand how I the only one how face this issue too times in the row?
And how there is none talk about it???
i know it's frustrating when you're stuck and it seems like it just won't work. maybe take a few days off and look at it when you're refreshed - it helped me in the past and it keeps you sane
thanks for the advice
if you could set up a minimal example of the issue and invite me to the github repo i also could take a look at it
ok i will try
What is your name in github?
Because they did it differently from you
They did it more similarly to how I described above
Like this
I DID THE SAME JUST LOOK!!
the different is I change the way the logic is place and how it work
it doesn't explain why i get the end position of the touch when i press out of game scene
I did the same in the video
like same same
and it work
but my code still does not work
Yeah that's a big difference
Hey this might sound really weird but obviously when you press a button you can either use space bar or click with the mouse, is there a way to remove the ability to press with space bar and either just keep it as left click or change to another key ? Thankyou
If I want to make a Virtual Mouse, because I want to unify both console and actual real mouse I/O for content like UI or gameplay-wise like shooting, but I don't think I want any of the additional content there is in VirtualMouseInput such as graphics or the actions there are, should I just create a Mouse myself and update its position manually?
Rather confused on how to approach this
Nevermind I suppose...? You can't have Virtual Mouses and use UI Toolkit?
I think the Virtual Mouse package specifically uses uGUI to visuals of it, but the underlying clicking and stuff would work with ui toolkit too
And if so then you could add a canvas just for the virtual mouse, or you can write your own wrapper that does the same as the virtual mouse to simulate a mouse and use your own display method for it
Oh, yeah, basically what you wrote here. Just check how the Virtual Mouse package does it
Is there a way to activate the stacktrace for input? Like, when doing Debug.Log it currently hides stuff in the input and inputsystem namespace from the stacktrace
edit: Ended up just generating my own stacktrace and printing that
Has anyone had trouble with getting PlayerInputManager to notice its JoinAction rebinding to a new button? I'm not sure if I'm rebinding wrong or it's a bug with PlayerInputManager.
Boiled down my rebind script to as little as I could. Also attached a *.zip of me isolating the issue in a unity scene in my failed attempt to figure out what's going wrong.
public class IsolateRebindBugRebinder : MonoBehaviour
{
[Tooltip("Key to press to initiate an interactive rebind for the join key.")]
[SerializeField]
private InputAction rebindJoinKey = new InputAction("rebindJoin", binding: "<Keyboard>/r");
[Tooltip("InputAction to be perform rebinding on.")]
[SerializeField]
private InputActionReference join;
private InputActionRebindingExtensions.RebindingOperation rebindOperation;
void OnEnable()
{
rebindJoinKey.performed += RebindJoinKey_performed;
rebindJoinKey.Enable();
}
private void OnDisable()
{
rebindJoinKey.Disable();
rebindJoinKey.performed -= RebindJoinKey_performed;
flagRebindOpForGarbageCollection();
}
private void RebindJoinKey_performed(InputAction.CallbackContext obj)
{
join.action.Disable();
rebindOperation = join.action.PerformInteractiveRebinding()
.OnComplete(onRebindCompleted)
.Start();
Debug.Log("You pressed the rebind key " + rebindJoinKey.GetBindingDisplayString()
+ ". Press the new key you'd like to use for the join action.");
}
private void onRebindCompleted(InputActionRebindingExtensions.RebindingOperation operation)
{
join.action.Enable();
Debug.Log("join key was rebound to " + join.action.GetBindingDisplayString());
flagRebindOpForGarbageCollection();
}
private void flagRebindOpForGarbageCollection()
{
rebindOperation?.Dispose();
rebindOperation = null;
}
}
From the docs for PlayerInputManager.joinAction:
If the join action is a reference to an existing input action, it will be cloned when the PlayerInputManager is enabled.```
So really the issue here is that you have your own separate reference to the input action. You should rebind the one from the PlayerInputManager component directly.
Thanks for finding that bit of doc I missed! It worked by adding a reference to PlayerInputManager's JoinAction in my onRebindCompleted()!
private void onRebindCompleted(InputActionRebindingExtensions.RebindingOperation operation)
{
join.action.Enable();
PlayerInputManager.instance.joinAction.action.ApplyBindingOverride(0, join.action.bindings[0]);
...
}
Now I just need to look into a way to get the bindingIndex from join.action instead of hard coding 0's.
Can anyone help me
key binds dont work anymore in my unity game after restarting
That's too vague to diagnosis. Issue could be that:
- The device linked to those key binds is no longer connected to your computer.
- After you've verified your computer accepts the device functions, verify Unity's InputDebugger sees it.
- After that, set a breakpoint in the code that responds to the keybinds to see if your code is at fault.
- If the breakpoints aren't hit, try making a new Unity project to see if the key binds can be hit in a fresh project.
- After you can get them hit in a fresh project, figure out the diff between that fresh project and your old one.
Is there a preferred way to sync overridePath/rebind data among clones that have been created of an InputActionAsset? Is using AppplyBindingOverride() on PlayerInputManager.instance, PlayerInput.all, and other clones the recommended way?
why i cant drag anything here?
Probably because you used the legacy types
Your objects are probably TMP_InputField
So you should make your fields TMP_InputField
that was the issue, thanks for your reply
Hello, I am trying to get the Input System Package working with a scroll wheel input and I am having quite a bit of trouble.
I would like to create a "zoom" function where my mouse scroll wheel is the user input. Scrolling up should zoom in, scrolling down should zoom out.
I have configured my input system action for Zoom to use a 1D Axis (since I cannot find any alternative). This gives me a Negative and Positive input, I have bound these to Scroll/X and Scroll/Y respectively. The issue is that no matter what I do, the result of these inputs is always identical. I currnetly have this in my code to read the value:
InputAction zoomAction = InputSystem.actions.FindAction("Zoom");
float zoomValue = zoomAction.ReadValue<float>();
Right now, zoomValue is always 1 regardless or when way I scroll my mouse wheel. How can I get the proper axis value so that I can distinguish which way the user scrolled? I.e I would expect the values -1 and 1 so that I can multiply this by a zoomFactor to control camera zoom.
I have tried inverting the input value with a processor, but this seems to be ignored for the 1DAxis values
Small update on this, after some playing, I set the parent Zoom to be an axis input and I now get negatives and positives, but I can see that Debug.Log is logging 0 as my zoomValue, missing about 99% of my mouse scrolls. If I scroll REALLY fast (by unlocking my scroll wheel and letting it rip), I can get about 50% of frames reading an input.
This is running in Update and it is logging the 0 value for every frame, so it is not that the update is missing the update, seems like maybe the value is being floored? Or otherwise cast to an int? I cannot find any setting for this. 
Thanks to monkey with a typewriter theorem, I got it working. Wish the docs for this were newer than 2021 😔
Hard to call this the "new" input system when the docs are 4 years out of date.
Scroll X is the horizontal scrolling
which is not the usual thing you think of for mouse scroll
Scroll Y would be usually what you want
having them both bound to the axis is quite weird.
YOu certainly wouldn't use a composite binding for this
I now have set this to Scroll/Down and Scroll/Up, though because this is called an axis, I would expect it to allow for a single axis as the input and to give me the negative/postive value of the axis. Using Scroll/Y seems to be invalid as an axis here as it only corresponds to an up movement on the mouse wheel scroll.
You can bind it to a single thing
There's no reason to use a composite
Your problem is you made the binding itself a composite binding
Ah, ty, I misunderstood what you meant by this.
Would you happen to know how to achieve this in this unity version? I would like to just specify that zooming occurs on the Y axis, but I cannot find a way to get this to work, nor can I find any examples of doing this in unity 6
opening Unity right now to show you
this works
One thing you need to do is make sure you actually have the game window focused as you scroll though
it won't pick up the input if the game window is not focused.
@oak steeple
Oh and the code is just action.ReadValue<float>()
Thank you! That is so simple, lol.
If I wanted to bind the - and = key to the same input, would that just be a 1D axis then?
for keyboard keys then you'd add a compisite binding yeah
postiive/negative binding
(the = key is really the + key)
I suppose that just works.
Follow-up question on that though: If I zoom with the scroll wheel, the zoom moves at a good speed, but when I use the - or = to zoom, it zooms 10x faster. The code is pretty much just this:
void ZoomCamera(float zoomValue)
{
var newOrthographicSize = Mathf.Clamp(mainCamera.orthographicSize + (zoomValue * cameraZoomFactor) , minCameraZoom, maxCameraZoom);
mainCamera.orthographicSize += cameraZoomFactor * zoomValue;
}
// Update is called once per frame
void Update()
{
float zoomValue = zoomAction.ReadValue<float>();
ZoomCamera(zoomValue);
}
Did I bork something? Or will I just need to discriminate between mouse wheel and - or = inputs and handle them differently?
yeah so
those are two different styles of input really
the key is going to return 1 constantly while it's held doiwn
the scrollwheel only gives you value as you're scrolling
it might be simpler to just use two separate actions here
because the input handling style needs to be totally different due to how those two different controls work
although
I think it's possible adding this "Press Only" interaction to the keyboard binding might make it work similarly?
Give that a shot
nah it doesn't haha
yeah, it shouldnt be a big deal, I can just reduce the zoomFactor for those key presses, just always want to make sure I am not straying too far away from good practice
hmm this might work tho...
void Update()
{
if (Action.action.WasPerformedThisFrame()) {
Debug.Log(Action.action.ReadValue<float>());
}
}```
yeah this works
it will make it so you have to keep pressing hte - = keys to zoom
instead of holding
not sure if that's what you want or not
really if you're handling it in update and you want holding behavior, you will want to multiply it by Time.deltaTime, but only for the keyboard holding, not for the mouse scrolling
so that would necessitate two separate actions I think.
yeah, I also need to play with how Orthographic size works with my pixel art (so multiplying by deltaTime might cause issues with the zoom factor), I have heard it can create issues if not scaled correctly
I am a noob though
Using a Scale processor on either the scroll wheel or the -/+ binding might do the trick.
It won't make the keyboard zoom compensate for varying framerates though
Oh but there's a DeltaTime scale processor!
That would help
Ohhh, that is neat, tyty.
I am very aquainted to handling this all in code, so trying to learn more about this input system
yeah I normally handle most of it in code myself and avoid processors
but - I guess they can be useful.
Hello,
I am developing mobile game where I am using new input system, c# jobs and ui toolkit. In my game, I have a button that, when held by the player, spawns specific objects. For that I am using:
RegisterCallback<PointerDownEvent> -> calling function to start spawning objects
RegisterCallback<PointerUpEvent> -> calling function to stop spawning objects
This works on all tested mobile devices except for one that has an Samsung S Pen. When a player with an S Pen holds the button, sometimes the S Pen correctly detects the hold for the entire time, but other times, the PointerUpEvent is called shortly after the touch, even though the S Pen is still touching the screen.
My second issue with the S Pen is that only with it, strange and unpredictable things happen after a random touch—things that don’t make sense and aren’t programmed. Specifically, in my C# job, I have a particle simulation that isn’t affected by input in any way, yet sometimes, after hovering or touching with the S Pen, the particles inexplicably teleport off-screen. When the S Pen is inserted back into its holder, this strange behavior does not occur.
I didn't find any patterns in it, and only this error appeared in the game development console, but I'm not sure if it's related to it:
#0 0xd146/0c7 (libunity.so) Platform Stacktrace:GetStacktrace(int) 0x22
#1 0xd14b6887 (libunity so) Stacktrace::GetStacktrace(int) 0x2
#2 0xdleafa?! (libunity.so) DebugString ToFile(Debug String ToFileData const&) 0x196
#3 0xd0b2a351 (libunity.so) DebugLogHandler Internal Log(LogType, LogOption, core: basic_string<char Core::StringStorageDefault<char> const&, Object) 0x6a
#4 0xd0b2a2c7 (libunity.so) DebuglogHandler_CUSTOM_Internal_Log(LogType, LogOption
BindingsManagedSpan, void) 0x3a
#5 0x8405c59a (Unknown) ? OxO
Do you please have any ideas how to fix this issues? Thank you very much! 🙂
report a bug to Unity about the S Pen and the unexpected pointer behavior, probably?
Sure, I'll send it. I just wasn't sure if I might be doing something wrong. Thanks! 😊
could someone tell me real quick what the action for Look has to be , is it pass through or axis , i tried so much i cant get it wroking
Debug.Log(lookAction.ReadValue<Vector2>());
this just does not give me any values
i remember i had to change something but i cant remember what it was
ah never mind it is one of those unity bugs..
a new project works as it should be
How do i work with the new input system and mobile gyroscope ?
It should be Value/Vector2
How would I capture at the very least either a deviceID or an InputUser, just anything that lets me know who pressed a button in UI Toolkit? I'm reading and searching across the docs and all I can see is making it compatible with uGui which requires replacing their event system with the Input System's but I cannot find something about "getting who clicked the thing" or similar
Everything from Unity +2022 should be working out of the box according to the docs as well
I should note that I'm not using the PlayerInputManager or PlayerInputs
The most I've gotten was something like
public class ButtonInputHandler : MonoBehaviour
{
[SerializeField] private UIDocument uiDocument;
[SerializeField] private InputActionAsset inputActions;
private InputAction interactAction;
void Awake()
{
// Find the Interact action in the UI action map...
// This... doesn't work in multiplayer because anybody performing the action would be picked up...
// even more, it doesn't care if you're actually pressing the button or not...
var uiMap = inputActions.FindActionMap("UI");
interactAction = uiMap.FindAction("Interact");
// Get the root visual element and button
VisualElement root = uiDocument.rootVisualElement;
Button actionButton = root.Q<Button>("action-button");
actionButton.clicked += OnButtonClicked;
interactAction.Enable();
interactAction.performed += OnInteractPerformed;
}
private void OnButtonClicked()
{
Debug.Log("Button clicked in UI Toolkit!");
}
private void OnInteractPerformed(InputAction.CallbackContext context)
{
// Get the device that triggered the action
InputDevice device = context.control.device;
int deviceId = device.deviceId;
Debug.Log($"Interact action performed by device ID: {deviceId}");
// Get the InputUser associated with the device (if any)
InputUser? user = InputUser.FindUserPairedToDevice(device);
if (user.HasValue)
{
Debug.Log($"InputUser ID: {user.Value.id}");
}
else
{
Debug.Log("No InputUser associated with this device.");
}
}
}
Which is frankly, insane, and I can't even think how I would communicate the data found in OnInteractPerformed to the button subscribers. It simply just doesn't work.
Maybe create a cursor (pool?) which are linked to InputUsers and whenever the button is pressed look at the cursors for who was hovering it? But then the cursors can overlap and nobody knows, that's also an additional whole system to query info for instead of being offered in the button event...
Alternatively a "owner player ui" so i already know who's pressing it, but I still have the issue of data not being passed through the event to subscribers and I still don't know who's pressing things so I'd have no way to block other users from pressing the button
I'm been researching a bit more and from my understanding is that I could probably use
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/UISupport.html#multiplayer-uis
And then track every the events generated back to the system that generated them, maybe?
Reading some more and only one EventSystem can exist, in both Unity's and UI Toolkit's, which brings me to MultiplayerEventSystem and its InputSystemUIInputModule, but according to the manual When working with Unity UI (uGUI), or when using UI Toolkit in versions of Unity prior to Unity 2023.2, you must use the UI Input Module component which defines which actions are passed through to your UI, as well as some other UI-related input settings. Brings me to believe that it's entirely optional as I'm in Unity 6 and I'm going in circles
Unless using MultiplayerEventSystem makes InputSystemUIInputModule entirely required, maybe some clarification would be nice...?
Was there ever any followup on this?
I've got a system with multiple control schemes (RTS, first/third person) and the player is able to activate a "build mode" in either but there are cases where build mode controls need to override different controls in each mode (e.g. the scroll wheel handles zooming in/out in the RTS control scheme, while it handles swapping weapons in the FPS/TPS control scheme) to do the same thing (in build mode it should rotate the object you're building).
Just wondering if this layered action map thing ever got implemented in any capacity before I go and implement my own wrapper, can't find anything relevant in docs.
Considering that the last few replies were about "still dreaming" and some user complaining about having to make their own wrapper... tough chance
I think you'll need to write your own wrapper
The issue is rather old so I'd go check around first if anybody has made their own implementation
eh, it's more trouble integrating someone else's code into my project
can you tell I've been a C++ developer for several years
okay yeah I didn't realize forums did the infinite scroll thing and not pages now, I guess the idea was to use the timeline thing on the right side lmao
I suppose this could be done using bindingMask, but this is ugly as shit lol
This is rebinding the action map itself, I don't think that'd be like, a good idea for gameplay
specifically looking at LoadBindingOverridesFromJson
I personally would just have an enum or something with a switch and call Actions.Gameplay.Enable() or Actions.Build.Enable(), and whenever you enable one or the other the other gets .Disable(), if I understand correctly what you want to do...
nope
build needs to be enabled concurrently with the main control scheme and override its bindings where applicable, while retaining those it doesn't override
Okay so its not a WHOLE map, but rather selective actions
Hmm yeah that's complicated
It's an action map in the literal sense, but it's not a control scheme in the colloquial sense
Action maps do support multiple concurrent action maps (e.g. I have the pause button always enabled lmao)
Yeah that's also what I'm doing (with debug lol)
It's just that you can't set input actions to be consumed, so if you press space, it'll be plumbed through to every active action map :')
Right now for testing purposes I just have "build mode" jammed into a bool in the main game class 💀
but long term I don't wanna have two divergent code paths (one for RTS controls, one for FPS/TPS controls) handling the exact same thing, since that'd just be silly
oh well, I'll figure something out, it's not a particularly complicated idea in the first place - just working around the unity API as usual
On top of my head right now I'd look if I could write a helper method that enables the RTS action map and then selectively goes through each action individually of the FPS/TPS action map would be possible, instead of the Action Map itself
Extremely hardcoded solution specifically just for this sole gameplay solution
But I haven't gone down there yet so I don't even know if you can disable actions individually
(I imagine you can)
Either that or do bizarre stuff like action processors or modifiers or so
Yeah, you can disable them
hmm, the annoying thing here is also gonna be dealing with runtime control rebinding (e.g. someone who wants to put rotate on Q/E instead of the mouse wheel)
That's why I think that keeping it to the actions would be the best way instead of doing something like a JsonOverride
well, that's the thing, if changing the key eliminates the relevant binding conflict, then you don't want to disable the lower priority binding anymore
so if they've rebound rotation they should be able to zoom with the mouse wheel again
so i guess it's more that i want input actions to be able to consume key presses lmao
I have written fully custom input systems from scratch in the past with full support for this exact kind of thing, but not for Unity, it was in C++ - so I was just intercepting win32 messages and routing them to the input handler
I'll have to sit on this and just keep doing the placeholder thing for now I guess, thanks for trying to help though
also so as to not totally steamroll what you originally asked - bro did not receive an answer to this one, so if anyone's reading this who knows, feel free to reply :p
(I'm not familiar enough with the UI toolkit to know anything here, sorry - I'm just writing my own UI through code around the older Unity UI for the sake of mod support)
Try looking into maybe (?) writting some kind of class manager that wraps an action maps and registers processors to the Actions, then within that class you can do stuff like if (BuildModeShadowsAction(action)) then you don't process that input, and in the build mode attach to every single action something like a consumer processor that just disables the Action Map
Literally just made this up right now, don't even know if processors allow you to do something like that but they are events so maybe?
This is more like "A reason for why to look into action processors" because I just don't know how they function or how to use them and how far you can get with them, other than the default baby ones like normalize or invert or w/e
I really don't know how moddable my project would be because it's all DOTS so that just wrecks the typical Bepin plugins but I'd say that UI Toolkit could be better for it considering (afaik) it's just one single component and a XML-like document file
So instead of defining UI gameobjects you just load the XML into a single MonoBehaviour and be done with it, it even has CSS so you can just style it with ease
so you have the option to have the input system generate a .cs file that already does this
and you can modify that file, it'll just get generated over again if you make changes
could maybe use a partial class and extension methods though
like this shit's all auto generated lmao
UI toolkit sounds more moddable, I can't remember why I chose not to use it honestly
oh that's why i chose the old UI
I wrote my own XML content loader anyway
FWIW when I say moddable, I mean I'm developing the game for direct mod support similar to what Rimworld and Kenshi have rather than mods for games like Abiotic Factor of Risk of Rain
UI Toolkit now has worldspace UI, but shaders are still an issue
...I don't quite follow the "easy referencing from MonoBehaviours" though
oh UI toolkit has worldspace? wacky
...I believe so! I read about it, I think its Unity 6 though?
if you're working on something where you want to reference the UI component from other scripts, or to be able to instantiate UI from scripts
i just so happen to be on 6 lmao
Oh right I guess the ease of "it's just a single component and a single xml" takes away from "GetComponentInChildren" and stuff
I'm doing as little work in the editor as possible, FWIW
yeah, it's basically condensing the older component hierarchy model into a single element that's more like FXML or WPF
You have to instead use things like search by name
this is partially because I have literally 0 need to author content in the editor and partially so I don't have to make modders create Unity projects to preview their shit lol
i fear the amount of magic strings that will be born from this
I kinda want to do this but with specific game logic like weapons or projectiles or enemy waves / pools
Oh also player models believe it or not
I mean that's fairly straightforward I think, a lot of games do XML-based content
i.e. you define all your weapons, equipment, etc. through XML
You just have to have a extremely strong serialization and deserialization system
eh, C#/.NET has builtins if you can put up with it
personally I got sick of the builtin .NET XML stuff
still slightly more complicated than doing something like a ScriptableObject and calling it a day
oh for sure
some people swear by scriptableobjects but
not my thing
I used them in past projects for preset stuff like movement controller parameters
I just feel like they get a bit more annoying to manage in large quantities :p compared to a text file where I can just ctrl+f something and do mass replaces if I need to
For me it's using DOTS why I want it to be easier to modify, kinda maybe slightly inspired by source's vpks where it's just a filesystem and you can overwrite whatever you want in the game without needing a editor or sdk
also we've gotten fairly off topic, whoops
not a huge problem if it's not steamrolling other people asking questions but probably best to move the conversation somewhere idk
I was thinking that as well
Hello,
it is possible in new input system disable pen input? Thank you! 🙂
disable it in what context? Can't you just not bind it to anything?
Hello, we were writing about it maybe 5 days ago, in my mobile game Spen (pen from samsung) is doing strange things
- sometimes its detecting tap not hold, when is pen still touching screen
- messing my game for some strange reason (affecting core simulation, even when is nothing like that programmed)
I wrote bug to discussion forum, but noone replyed so far, so my idea was to completely disable pen to not trigger any events...
P.S: I am using new input system with ui toolkit, so I am detecting holding button via registercallback pointerupevent and pointerdownevent (I am using this, because on pointerdown event is water opened and on pointerup is closed)
For example i didnt bind hover effect, but it is still triggered and somehow its affecting my simulation core which is programmed in c# jobs.. and none input interaction with simulation is programmed
What is the binding for the left stick press on playstation controller? I cannot seem to find it inside the input system.
is there a way to make it so the input system only calls the function once even if the button is held? even when its tapped it gets called more than once.
I tried setting the bool false right after but that's just too quick.
(I have my other scripts reference the input handler script and use the bools to trigger actions like a jump).
It does only call it once
Your problem presumably is you're reading that bool variable in Update
So you're doing it every frame
what should i use to read the bool though?
I recommend not having it
It's an antipattern
Read this conversation I had yesterday with someone who was using the same pattern:
#💻┃code-beginner message
thank you
In the new input system, how do I make it detect only one press of the arrow keys, while getting their value?
what do you mean by "detect only one press". As opposed to what?
I want to make it so the player can choose options from the menu using the arrow keys. I implemented a counter that highlights the selected button, but even the slightest push from the arrow keys causes the counter to go right to the last button
Menu navigation is included out of the box in the UI system for free, with no need to implement it yourself
anyway it sounds like you're doing something like checking if it's currently pressed in Update
You would need to share your current code - but most likely oyu need to switch from IsPressed() to WasPerformedThisFrame()
but I do recommend you simply use the built in navigation rather than reinvent the wheel.
I'd rather code it myself
{
pauseOpen = pauseOpenAct.WasPressedThisFrame();
pauseClose = pauseCloseAct.WasPressedThisFrame();
playerVector = pmAct.ReadValue<Vector2>();
jumpPressed = jumpAct.WasPressedThisFrame();
jumpFreed = jumpAct.WasReleasedThisFrame();
menuVector = mmAct.ReadValue<Vector2>();
menuChoose = mcAct.WasPressedThisFrame();
}``` In this input manager
ugh
terrible pattern
don't do this
refer to this conversaion I had the other day (and again right above you in this channel)
you are making your life much harder with this pattern
{
selectButton();
}
public void selectButton(){
numButton=(int)Mathf.Clamp(numButton-inputManager.instance.menuVector.y,0,buttonHolder.transform.childCount-1);
Debug.Log(numButton);
for(int x=0; x<buttonHolder.transform.childCount; x++){
buttonHolder.transform.GetChild(x).GetComponent<Button>().image.color=x==numButton?Color.red:Color.white;
}
}```
The functions in the menu manager that highlights the buttons
you're doing this every frame
so yeah of course it's going to go lightning fast
So when should it be done then
Only when you first actuate the stick (or first press the key)
Do I use WasPressedThisFrame()?
Again i really recommend just using the built in system
If you want this to work with joysticks as well as the keyboard, you're going to have to distill the vector down to a cardinal direction, and then compare the current direction to the previous direction to see if it has changed
the built in UI navigation does all this out of the box
How do I use the built in navigation system then?
It should pretty much be working out of the box assuming you haven't done anything weird and you're using UGUI
you may need to manually select one of the buttons/UI elements in Start or something to kickstart it
You may want to double check the highlight colors etc you have set up on your buttons too
@austere grotto Thanks, it works
For my "Move" (LeftStick [Gamepad]) Input Actions Binding, I could not find an option to replicate GetAxisRaw, and so the closest I've come is by code ("Round"):
void OnMove(InputValue inputValue) {
Vector2 inputAxis = inputValue.Get<Vector2>();
// inputAxis = new Vector2(Mathf.Round(inputAxis.x), Mathf.Round(inputAxis.y));
Debug.Log(inputAxis);
I've disabled Rounding and using Debug.Log to demonstrate.
Some comments in other channel are:
Chris: inputValue.Get<Vector2>() kinda is the equivalent of GetAxisRaw
rb5300: Maybe this? https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/Processors.html#axis-deadzone
In my experience, @fierce compass,when I Debug.Log the value of inputValue.Get<Vector2>(), it's showing decimal numbers, not whole numbers.
@small quest , I've checked that doc now, and I've tried 0.5 for min and max, but this doesn't appear to change anything.
Without whole values, I can never get "isMovingLeft" to be true, like it is when I use Round.
I've been having a hard time with this. I did however finally get Player Input Manager working to add players manually, so that my 4 children player objects (with Player Input components) are automatically added.
"An axis deadzone Processor scales the values of a Control so that any value with an absolute value smaller than min is 0, and any value with an absolute value larger than max is 1 or -1."
its description sounded like what you wanted tbh
You can also make your own processor to do this rounding
I see the docs for writing my own custom processor. I just wonder, am I really the first person in 5 years to want a GetAxisRaw equivalent.
getaxisraw also does -1 to 1, no? it's supposed to give decimals
For GetAxisRaw, the value is not smoothed like it is here. "The value will be in the range -1...1 for keyboard and joystick input. Since input is not smoothed, keyboard input will always be either -1, 0 or 1. This is useful if you want to do all smoothing of keyboard input processing yourself."
Wait, that quote is emphasizing keyboard input for no smoothing. But, in my experience, I was using a stick on the old input system and getting absolute values of 1, -1, or 0.
Creating my own processor, I'm stuck at ```csharp
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
oh, I added using UnityEditor above [InitializeOnLoad]
yeah, it's working now.
The type or namespace name 'Switch' does not exist in the namespace 'UnityEngine.InputSystem' (are you missing an assembly reference?)
Is Switch only available in Switch builds?
that's odd, i feel like it shouldn't do that
i mean, it's an axis
it's supposed to be analog
the new input system doesn't give smoothing there, it isn't GetAxis
it's just giving actual analog values
it sounds like you were getting bad values from the old input system
Strange. I also was experiencing a problem with the old input system where one of my controllers (F310 Logitech Gamepad) GetAxisRaw was always (1, 0). The other controllers (XBOX 360) worked fine (0, 0). This forced me to start using the new input system.
I've got an "binding with one modifier" action for alt-Z, but Z-alt is triggering it when I would only expect alt-Z to trigger it. Why is it triggering when the modifier is pressed instead of when the binding is pressed / how to make it work as I want? (This is not about hitting Z by itself like all the topics I found about modifiers)
- I want to bind a label to two ints: a simple "X/Y" display. But "text" bindingID can only take one property. So. I presume there's no double-binding and I'm gonna have to make struct with the two
Is this an input system question or a #🧰┃ui-toolkit / #📲┃ui-ux question?
Yea I'm just sitting in the same channel still
Hey i have a silly question - my ui is not working at all with the new input system. Keyboard input works as usual but ui not at all
public class PlayerInputHandler : MonoBehaviour
{
#region Private Fields
/// <summary>
/// Instance of the input system actions, which contains all input action maps and actions.
/// </summary>
private InputSystem_Actions _inputSystemActions;
/// <summary>
/// Tracks whether the input system has been initialized to prevent redundant initialization.
/// </summary>
private bool _isInitialized = false;
#endregion
#region Public Properties
public InputSystem_Actions InputSystemActions => _inputSystemActions;
public Vector3 MousePosition => Mouse.current.position.ReadValue();
#endregion
#region Public Methods
/// <summary>
/// Initializes the input system actions and enables them.
/// This method is called via dependency injection to ensure the input system is ready for use.
/// </summary>
[Inject]
public void Initialize()
{
// Prevent redundant initialization.
if (_isInitialized)
{
return;
}
// Initialize the input system actions if not already initialized.
_inputSystemActions ??= new InputSystem_Actions();
// Enable the input system actions to start listening for input.
_inputSystemActions.Enable();
// Mark the input system as initialized.
_isInitialized = true;
// Log initialization for debugging purposes.
Debug.Log($"{nameof(PlayerInputHandler)} initialized.");
}
#endregion
}
It does not even work in a completly new scene with just a button
NEVERMIND! It was the problem that i had the mobile simulator open 😄
On-screen stick doesn't work.
Here's my InputAction control scheme:
WASD works here
But the on-screen thumbstick doesn't work
Keyboard P2 doesn't use the WASD, so this control scheme is definitely active
Made a script to track the current input device, but when using controller, it will randomly throw in keyboard inputs for some reason. I've tried a few different controllers so I know that's not the problem, any ideas?
https://paste.mod.gg/ramzijjwxhrn/0
A tool for sharing your source code with the world!
it also seemed to happen differently on switch controller vs xbox
on switch, sometimes every part of an input would be read as keyboard, but on xbox it's usually only part of the input
here's what it actually looks like if this helps
only playing on controller
Why don't you also print out which action was triggered and with what value?
that would give more info
for xbox it gives arrow keys and space
space is not used in my controls so it must be triggering that on its own
xbox?
Open the input debugger
you must have some rogue device plugged in or something
or your cat is on your keyboard
it only happens when doing inputs on the controller
so I doubt its something else
Ok. So starting from the start.
The PlayerInputActions asset:
Then I generate the C# class from it.
Then I have this class that holds the PlayerInput and PlayerInputActions:
public class PlayerActionsReporter : MonoBehaviour {
public PlayerInput PlayerInput;
public PlayerInputActions PlayerInputActions;
void Awake() {
PlayerInputActions = new PlayerInputActions();
PlayerInput.actions = PlayerInputActions.asset;
PlayerInput.user.AssociateActionsWithUser(PlayerInputActions);
PlayerInput.SwitchCurrentControlScheme(PlayerInput.defaultControlScheme Keyboard.current);
}
}
I've done it this way, so I can have multiple control schemes for the same controller and allow multiple players play using the same device or different devices on the same machine.
Then I have this class for testing:
public class PlayerInputsLogger : MonoBehaviour {
public PlayerActionsReporter PlayerActionsReporter;
void Start() {
PlayerActionsReporter.PlayerInputActions.ActionMap.Movement.performed += _ => Debug.Log($"Movement Performed");
PlayerActionsReporter.PlayerInputActions.ActionMap.Movement.canceled += _ => Debug.Log($"Movement Cancelled");
}
}
But when I move it in the scene, nothing happens:
not sure how it works when you manually assign an actions asset to a PlayerInpuit component but one thing to try is PlayerInputActions.Enable();
I would also try to rule out any control scheme stuff by... eliminating all of your control schemes
Thank you
The way I fixed it yesterday is by enabling it right after creating:
PlayerInputActions = new();
PlayerInputActions.Enable();
I mean, if it's supposed to be disabled by default, then why does the keyboard work?
A lot of people have this same issue: https://discussions.unity.com/t/on-screen-controls-not-working-correctly/786311/
I don't know
I think I've read about enabling it in that thread
Someone also said that they created their own onscreen stick component
In my case I just copied Unity’s component, but removed the parts where it uses the broken buggy Input system.
Isn't Unity not open source, what did they mean they copied it?
parts of it are open source
including the input system
most of the packages are open source
That should be very useful to create my own component, like my own BoxCollider2D but I'd like to work differently to easily mutate hitboxes: instead of only allowing to set location and size, I'd like to also be able to set positions top, bottom, left and right edges of the square.
Because right now I often find myself calculating manually the appropriate location and size, so that my walls end at the correct locations.
Like if I want to make another collider at the top to the current one that's also twice as tall as the current one.
Now I need to do math to calculate the correct position and size for it and there is no way to set the individual wall positions.
Now I have another issue with inability to dock the stick to the bottom right corner:
It gets bugged and disappears once I press on the stick
Then I can't even press on it again after I press it first time.
I guess I can still dock it to the center and use a canvas scaler and get pretty much the same effect here.
Or I can't. It disappears away from the screen on different aspect ratios.
The key works only the second time you press it. So i have to press it twice to toggle fullscreen. Does anyone know why?
It's the screen toggle that is making it do this but i don't know why. It's not about window focus, because other keys work.
I tried with keys like F11 and M and it's the same result. I tried delaying the fullscreen toggle. No matter what, the game ignores the first time i press the key.
I'm absolutely baffled
void Update()
{
if (fullScreenAction.WasPressedThisFrame())
{
Debug.LogError("fs key pressed");
// It's in fullscreen already, switch to windowed mode
if (Screen.fullScreenMode == FullScreenMode.ExclusiveFullScreen ||
Screen.fullScreenMode == FullScreenMode.FullScreenWindow)
{
Debug.LogError("to windowed");
Screen.fullScreenMode = FullScreenMode.Windowed;
}
else
{
Debug.LogError("to windowed full screen");
// Switch to windowed fullscreen
// Screen.fullScreenMode = FullScreenMode.FullScreenWindow;
Screen.SetResolution(Screen.currentResolution.width, Screen.currentResolution.height, FullScreenMode.FullScreenWindow);
}
}
}
still haven't been able to find more info on this problem, I'm not sure where I would even start looking for a fix
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
[Header("References")]
public Rigidbody rb;
public Transform head;
public Camera camera;
[Header("Configurations")]
public float walkSpeed;
public float runSpeed;
[Header("Runtime")]
Vector3 newVelocity;
void Start() {
// Nasconde e blocca il cursore
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
void Update() {
// Rotazione orizzontale
transform.Rotate(Vector3.up * Input.GetAxisRaw("Mouse X") * 2f);
float speed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
float inputX = Input.GetAxisRaw("Horizontal");
float inputZ = Input.GetAxisRaw("Vertical");
// Ignora piccoli movimenti involontari
if (Mathf.Abs(inputX) < 0.01f) inputX = 0f;
if (Mathf.Abs(inputZ) < 0.01f) inputZ = 0f;
Vector3 inputDirection = new Vector3(inputX, 0, inputZ).normalized;
Vector3 movement = inputDirection * speed;
// Mantiene la componente Y attuale
newVelocity = transform.TransformDirection(movement);
newVelocity.y = rb.velocity.y;
rb.velocity = newVelocity;
}
void LateUpdate() {
// Rotazione verticale (camera)
Vector3 e = head.eulerAngles;
e.x -= Input.GetAxisRaw("Mouse Y") * 2f;
e.x = RestrictAngle(e.x, -85f, 85f);
head.eulerAngles = e;
}
// Clamp angolo verticale testa
public static float RestrictAngle(float angle, float angleMin, float angleMax) {
if (angle > 180)
angle -= 360;
else if (angle < -180)
angle += 360;
if (angle > angleMax)
angle = angleMax;
if (angle < angleMin)
angle = angleMin;
return angle;
}
}
i have a problem with this code. My player moves by himself when standing still, as if he slides by himself. It also happens sometimes that near the walls he is attracted by them and so if I don't "run" he can't get out of this force, can someone help me?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
have you tried debugging your values? if you're using a controller you might have to set a dead zone
i use only wasd for the movement and shift for run
have you tried debugging your input values to see if they're what you expect?
" 'C:\Users\My project (6)\Assembly-CSharp.csproj' does not support debugging. No bootable target found."
don't need to do that, just Debug.Log the values and see if they're what you expect
Where do I put this command? Do I need to create a new void? I haven't done programming in at least 10 years and I don't remember anything and I'm doing this work for my boss
a new void... those are methods
anyways, no, you would just put those where you want to check the value
ok
logs let you see into the code, you gotta put them where you want to check
The problem I found out is the world and not the player, how can I solve it? gravity is basic
wdym, gravity isn't straight down? your entire world is tilted?
it is not tilted, if you want I attach some screens and/or videos of what happens
update: This bug does not happen in Windows. Just on Mac.
sounds like a mac-only input system bug
When you said "player moves by himself" and "sliding", it made me think of a bug I encountered that I couldn't resolve. #🖱️┃input-system message
Am I just being stupid or what? Why doesn't this do anything?
When I add a debug statement it doesn't show when I hit the key I've supposedly bound to "OpenSkillTree"
have you tried debugging input, to see if the key is being registered?
the "Open Input Debugger" on your PlayerInput
also make sure it's set to "Send Messages"
I don't see any of that on the Input Actions window, or in project settings
on your PlayerInput
it's definitely reacting to me pressing K
but the scripts aren't
And it's set to Send Messages
with SendMessages, you don't need the CallbackContext parameter; to get a value, you would use InputValue instead, but since those are Button type, you don't need any parameter at all
CallbackContext would be used if you set it to "Invoke UnityEvents"
In that case I wonder if it's this other irritating bug where it's telling me "Value cannot be null" when it's not, because that's on the same script 🙄
that wouldve been helpful to know about...
Nope, it still didn't help. It's whining because the window doesn't exist yet so it thinks the value is null on start up, but even when I turn the menu on by default K isn't closing it
and I have K set to close it
yeah that's... correct?
why not just make a single action for "Toggle Skill Tree" and handle whether to open or close it in code
I need to disable the character controller and allow the mouse to show up, and I thought using the input system was supposed to easily facilitate that
that's pretty unrelated
you could do it with the serialized callbacks, but why not just do it all through code in a single method
void OnToggleSkillTree() {
if (skillTreeOpen) {
// stuff to close skilltree
} else {
// stuff to open skilltree
}
}
oh i just noticed opening and closing are on separate action maps, mb
i see what you're going for now
could you actually show the error then
here's the layout of the UI_StatTree in UIBuilder, and everything that error is whining about is still there
Here's the line it points out in VS
okkk so this is kinda outside the scope of the channel, im not familiar with how that UI system works
I think I'm gonna trash it anyway cause it's not how I want it to look in the long run afterall
it's all columns and rows, I want a circle spanning out like PoE (not as big)
just a quick reality check; it kinda sounds like you're conflating these systems
how the input system works is detached from how you actually open or close the menu or freeze the PC
Alright, I might be bashing my head against a brick wall I can just walk around then
thanks for your help! 🙂
that's not what im saying lol
i just mean; if you have an issue with receiving input, don't expand that issue to other surrounding topics
focus just on the input aspect
or in your case, you seem to have an issue with the UI handling; that's detached from the input system, you would fix that separately
just reduces what you have to think about to solve any given problem
Yeah that's what I mean, my shitty UI handling is the brick wall but I'm busy playing with the input system thinking it was that
and now I can feel my fingernail on the mousepad when I move the mouse so I think it's time for a break
rest well and good luck when you come back to it
Hey, I'm using the following code to detect mouse position
Input.touchCount > 0 ? Input.GetTouch(0).position : Mouse.current.position.ReadValue()
However when I'm on android (with WebGL) and I don't touch the screen, touchCount returns 0 et Mouse.current.position.ReadValue() return Vector2.zero
The documentation state The mouse that was added or updated last or null if there is no mouse connected to the system. however it is never the case for me
How can I detect that my user is on android/webgl and is not touching the screen?
Webgl is super sketchily supported but also - this code is very weird. Why is it using both input systems
Everything in the Input class is the old system
Ok I'm really confused about something. I'm getting this error:
InvalidOperationException: Cannot read value of type 'Vector2' from composite 'UnityEngine.InputSystem.Composites.AxisComposite' bound to action 'Player/Move[/Keyboard/leftArrow,/Keyboard/rightArrow,/Keyboard/downArrow,/Keyboard/upArrow,/XInputControllerWindows/dpad/left,/XInputControllerWindows/dpad/right,/XInputControllerWindows/dpad/down,/XInputControllerWindows/dpad/up,/XInputControllerWindows/leftStick,/XInputControllerWindows/leftStick/up,/XInputControllerWindows/leftStick/down,/XInputControllerWindows/leftStick/right,/XInputControllerWindows/leftStick/left,/Keyboard/upArrow,/Keyboard/downArrow,/Keyboard/leftArrow,/Keyboard/rightArrow,/XInputControllerWindows/leftStick/up,/XInputControllerWindows/leftStick/down,/XInputControllerWindows/leftStick/left,/XInputControllerWindows/leftStick/right,/XInputControllerWindows/dpad]' (composite is a 'Int32' with value type 'float')
By the looks of it, this error can be fixed by setting the corresponding action to Action Type "value" and Control Type "Vector2". You then add the bindings as 2D Vector composites. So why, then, could I still be getting the same error?
"Controller Movement" is tested with the Xbox control stick and that is the only control scheme of the three that actually works. The other two run an error like the one I posted above
The help I've found online always points to the Action Type being the culprit but I'm pretty sure I've already covered all the places that would cause this error.
This is the exact line that triggers the error because it can't get a Vector2 out of it.... even though as far as I can tell it really should be able to?
The options for my keyboard here just to show they're set to 2D Vector
If there's anything else I should post that would add necessary context then pls let me know
I tried making a new input system from scratch by adding one from the Player Input component when when I plugged that in... it worked fine. In spite of the fact that I swear the options selected are identical to mine
was it perhaps unsaved?
that was the first thing i thought of
if it was maybe it was just bad caching that mightve been fixed with a restart
It was definitely saved
Maybe bad caching. Because honestly that did not feel right at all. I'm really convinced I had everything covered that time
Can someone here help me out? I'm new to Unity, and I try to make a script, so my player, rotates in the direction of the mouse cursor, but it doesn't work.
using UnityEngine;
public class PlayerRotationHandler : MonoBehaviour
{
[SerializeField] float rotatingSpeed = 5f;
[SerializeField] InputSystem_Actions inputActions;
private Vector2 rotation;
private void Awake()
{
inputActions = new InputSystem_Actions();
}
private void Rotating()
{
Vector2 current = inputActions.Player.Look.ReadValue<Vector2>();
rotation.x += current.x;
Debug.Log(rotation);
transform.localRotation = Quaternion.Euler(0, rotation.x, 0);
}
private void FixedUpdate()
{
Rotating();
}
}
I am using the input system version 1.14.0. and the Default Action map.
The Debug log gives me a zero vector.
Okay, nevermind, I got it.
Any idea why my Mouse Position isn't reporting in the Debug.log? I'm holding right-click when I'm testing like the modifier wants. It's also part of the Keyboard scheme that I created.
It works when my Gamepad thumbstick/scheme is used.
public void OnAim(InputAction.CallbackContext context) { _aimInput = context.ReadValue<Vector2>(); Debug.Log(_aimInput); }
- how did you hook this code up to the input action?
- Are you moving the mouse?
For (2), yes. For (1), using the Player Input component.
so what's actually happening here? Is nothing logging (i.e. the code not running), or is the wrong thing logging?
If I use the mouse, nothing is logged. If I use gamepad, I get the Vector2 like I expect.
could very well be a control scheme issue
The callback isn't being fired when the mouse input is used, in order words. Not sure why.
I have both of them bound to the Keyboard scheme that I made. My keyboard inputs for movement (WASD) work fine as well.
if you do a regular binding without the modifier thing does that work?
Nope, unfortunately not.
Gonna restart the editor, who knows.
btw are you sure you want position?
and not delta
on the mouse?
delta is much more analagous to a joystick
I think so. Trying to do a top-down aim where I rotate the player after right-clicking, similar to an aim. Wanted to see if I could avoid doing a Raycast by just pulling the position and converting it to world space.
I wouldn't do those on the same input action - you'd have to put some nasty logic to check if it's the mouse or the joystick and then do your math no?
also you would need the mouse position whether you're doing raycast or not
I figure it's either (a) doing an if-check on the scheme, or (b) creating two separate functions to handle the different input actions. Which, yea, would probably be cleaner, but still have to code two things either way.
Doesn't work even if I switch it to Delta, aaaaah. I'll keep fiddling with it.
It's like my mouse is just not being received by the game lol
use the input debugger to check
but yeah that kind of thing really screams "control scheme issue" usually
Never used it before but I think I'm looking at it right... WASD is showing up on the Events list as I press them but my mouse is not.
Not even left, middle or right click. And it looks like inputs that I don't even have bound to an input action are showing up if I press them, but the mouse is not. It's like Unity isn't even capturing the mouse for some reason.
try restarting?
I restarted the editor a minute ago but that didn't work. I'll restart my PC real quick.
Restarting didn't work, so I deleted both of my Control Schemes like you thought - and now it does. No clue why that's the issue when my WASD was assigned to the same scheme and working just fine. Going to try re-creating them and see what happens.
Figured it out. My Keyboard scheme had the Keyboard as a Device Type, but not the Mouse. 😔
Is it possible to (with reasonable effort) get this list of bindings in the inspector, or do I need to manually type the paths?
I would go check the input system source code and find where this UI is written to see how they do it
The input system is open source on GitHub
I ended up just automatically filling it, but there are some property drawers in there (sadly marked internal) that might fit the bill.
Hey I'm trying to have split screen multiplayer, how can I differentiate between two controllers which are plugged in at the same time?
The input system has the PLayerInputManager and PlayerInput components to mostly automate managing this
It also happens to manage splitting the screen if you so wish
Wait really? I made my own system for splitting the screen but I'll check it out.
Hey all,
I want to add mobile inputs (buttons and joystick) by using new input system.
Is there a way to use On-Screen Control by assigning actions instead of buttons ? For instance, I have jump action, I want to assign that instead of Button South on gamepad.
Nope. It's an on screen control, not an on screen action
Hey folks, stumbled upon a weired problem and couldn't find the aswer online. Thought maybe someone here could help me:
I'm using the input system and have an action (Value, Vector2) with several bindings: 2 gamepad axis (Dpad and Left Stick) and 2 composits (WASD and USB Gamepad Buttons 3, 2, Trigger and 4 for a DDR mat).
When accessing the value via ReadValue I only get inputs from the first two. Any ideas what could cause this?
are they part of separate control schemes perhaps?
The keyboard Composite is, but as far as I am aware ReadValue ignores the active ControlSheme, no?
In any case the USB Gamepad composite uses the same controlSheme as the working gampad axis.
@austere grotto I know I can't use that component directly but I want to know if it is possible to have a script like that one but with action.
Why
what's wrong with using OnScreenControls in its intended form?
If I want to change the action button later I have to change that on this component too. But if I use action directly, it is changed automatically on this script too.
Is it not one of the problems which this input system tried to solve ? I wonder why we have key selection for OnScreenControl.
You need to think of the on screen control like a physical button on a controller
then the analogy will make sense
I want to think of it as an action.
Let me ask another question then, Is it possible to change ActionMap/Action to input control ?
found the answer (or at least part of it). Apparently the mat is considered a joystick, despite being recognized as USB gamepad. After enabling the binding for the joystick controlSheme it worked.
what does that mean exactly?
I've still got this question. How do I get a callback for modifier+binding to not trigger when the binding then modifier is pressed? ie alt-f4, not f4-alt.
implement it yourself instead of using the built in modifier binding thing
well, that is wild it's not a built-in feature to handle a very common thing like that
I'm finding that if I Disable() an ActionMap in Start(), it is somehow reenabled and triggering callbacks. I've Disabled action maps elsewhere mid-game and it works fine, but I just added a new map (for targeting) that should start disabled until I call Enable(). (Note this isn't for PlayerActions that seems to often have a similar problem) Alternatively I could subscribe/unsubscribed to the .performed of each action instead of enabling/disabling the map, but that's a bit much. Also maybe I could use some insight on how best to handle the context of input, e.g. the difference between mouse selecting a unit vs targeting a unit's action. Currently going with: turning on/off action maps.
While I'm here I don't suppose there's a way to debug breakpoint inside ActionMap.Enable so I could tell where it's being re-enabled...
You can put breakpoints in the input system source code to your hearts content
Yea that's some good rubberducking there, I should just try. I forget that package is in my project's library... still, what about core Unity source though
Well, Entering Play Mode turns them all back on, somehow after Start(), but also UI Toolkit is turning all the action maps on also, somehow even after the first frame, so I need to start a coroutune to wait 2 frames before turning off the action map.
why do i keep getting this error when i recompile or play?
where is it coming from?
How to swap sprites on OnScreenButton?
Like when it's pressed.
I am thinking to write my own OnScreenButton that would report when it's pressed and released and also swap sprites like the normal buttons do.
public class BetterOnScreenButton : OnScreenButton {
[UsedImplicitly]
public new void OnPointerDown(PointerEventData EventData) {
base.OnPointerDown(EventData);
Debug.Log("On-screen button pressed.");
}
[UsedImplicitly]
public new void OnPointerUp(PointerEventData EventData) {
base.OnPointerUp(EventData);
Debug.Log("On-screen button released.");
}
}
But this doesn't work. The button functionality itself works, but it doesn't debug print.
Interesting, explicitly defining that my class implements the interfaces: public class BetterOnScreenButton : OnScreenButton, IPointerDownHandler, IPointerUpHandler made it work.
I thought the inheritance is supposed to inherit the interfaces that are implemented in the base classes.
Ok this did it:
public class BetterOnScreenButton : OnScreenButton, IPointerDownHandler, IPointerUpHandler {
Image Image;
Sprite ButtonUp;
public Sprite ButtonDown;
public event Action PointerDown;
public event Action PointerUp;
public void Start() {
Image = GetComponent<Image>();
ButtonUp = Image.sprite;
}
[UsedImplicitly]
public new void OnPointerDown(PointerEventData EventData) {
base.OnPointerDown(EventData);
Image.sprite = ButtonDown;
PointerDown?.Invoke();
}
[UsedImplicitly]
public new void OnPointerUp(PointerEventData EventData) {
base.OnPointerUp(EventData);
Image.sprite = ButtonUp;
PointerUp?.Invoke();
}
}
you probably need to check settings on everything that uses input. Typically input is not enabled automatically, that’s one of the main features of input system to allow for deliberate control. Some systems like ui toolkit and the event system will enable their action map (not others), which is the general convention.
From the class that’s generated from the input actions asset
Nope actually, this wasn't working for me in InputSystem 1.11 but 1.14 ( maybe 1.12 ) works fine : just set the new Modifiers Order to Ordered. (Alt-z triggering callback but not Z-Alt)
Also maybe 1.14 wasn't needed and this InputSystem setting would've done it :
I remember seeing this setting and thought it prevented something like a "W" action being triggered when a "Shift-W" action existed. I guess it does that, but also and prevents "W-Shift" from triggering
"Enable Input Consumption" yup now I don't get Z-Alt triggering callbacks
hi my INputActions are not working
I am using the one directly from unity, I generated a C# Class, added another Script but it is not getting any input into the script, when I change bools from action, it works, but pressing the button to activate the action itself is not working
you'd have to show the code
did you remember to enable the instance of the generated class?
You named your method "Onable"
it should be "OnEnable"
also I would highly discourage this pattern of using intermediate variables to capture the input
how would you do it?
OMG
Check out this discussion I had recently with someone doing the same thing: #💻┃code-beginner message
basically - remove the middleman
or at least, simplify the middleman
With these middleman variables you're basically doubling the work and code you have to write for no real benefit
There's only one good reason to use a pattern like this and it's if you want to implement networked multiplayer or AI characters using an input packet command pattern.
I am planning on adding multiplayer and Ai characters
there's a lot more work to be done here then
you need to capture all the input and put it in a struct
that struct would need to be network serializable
then you would pass that struct around into your various character behaviour scripts to actualyl control the thing.
The Ai would generate these structs as if it were using its own input devices
And the input struct would be sent to the server in an RPC and then the server would control the character using them
If you are trying to make a networked online game and you haven't started the networking stuff yet, you should start it, yesterday
Networking is best introduced at the very beginning of the project.
ohh thats a good advice, im trying to add input system to a package I already have, but maybe I should start focussing on adding Networking forst
yeah this whole thing is going to depend heavily on which network framework you use too
I still dont know wich Im using, I have always had trouble with Unity netcode, but I havent tryed any other
Okay, Continuing from my problems which I thought were solved with "Enable Input Consumption"
Now my WASD camera panning input is not triggering at all, and if I turn off that option, it works
No other action uses any of WASD, so there should not be any "consumption" problems preventing that Pan from working
I'm perplexed but going to have to turn the setting off, then manually set the Modifiers order on my alt-z action, individually .
Hello there
does anyone know a way to read sixaxis data from a DualSense controller on PC?
I have a big question, Im changing camera rotation speed, but it seems that the speed its different from a gamepad or controller to delta or mouse, how can I have them be teh same? or should i mae different sensitivities for controller and mouse?
there really isn't any such thing as "the same" there. For mouse specifically, every user has different hardware and OS-level settings for their mice, and your game cannot possibly normalize them. The best thing to do is give your users generous mouse sensitivity settings and let them calibrate it.
but, should i have different values for a mouse sentivity and controller sentitivity
I have an Upd&Down and Left&Right Speed
wich seems nice when I use controller, but when using mouse, it is too fast
yes
I have the same Look input action, should I make one for mouse and another one for controller?
you should have a separate mouse sentivity
okay okay
why use Unity New Input system instead of just Input.GetKeyDown(KeyCode.SPACE) and other stuff?
Because it has several advantages such as:
- Good local multiplayer support
- Support for interactive runtime key rebinding
- Support for event-based input handling
- Support for custom devices
and more
If you don't need any of that, and you just want a very simple programming interface, it's fine to stick with the old one.
ohh ok ok very cool (nah ima learn it, I just always skipped it in tutorials cause i taught no one used it)
thanks for the info 🫡
Most people are using it other than people who are just getting started with unity.
Also afaik it's the default in new projects.
yea lol
It definitely has more of a learning curve though
alr thanks 👍
Hey y'all - I'm making a simple 2D top-down game where the user primarily operates via click and drag. Think of it like a slingshot, clicking, and setting a direction and a velocity, and releasing.
I'm trying to find the best way to do this using the new input system. I understand I could get away with static references to Touches or Input, but I'd rather learn the right way even if it means a bit slower going.
There are two approaches I can see working, and I don't know if one is obviously better than the other.
- Have each component instantiate a new instance of the generated input system code on
Awake. For instance, I can have aSlingshotControllerwith code likeprivate void Awake() { var input = new InputSystem(); input.GamePlay.Click.start += BeginSlingshot; input.GamePlay.Click.Canceled += EndSlingshot; }; - I can create some sort of generic set of interfaces like
IClickable, and then do object collision detection on the point that was clicked. This eliminates the boilerplate of injecting the actions system by itself and registering the event handles, but feels like I might be over-architecting it?
I'm also seeing solutions like using the PlayerInput component, and I don't understand yet what IClickHandler and how those events fit into the broader pattern yet.
You generally would want a shared instance, not one instance per component.
As for clicking and dragging and stuff though, there's a good argument to be made to use the UI event system for it - since it will automatically give you UI-blocking behavior out of the box, and you can use stuff like IDragHandler, IPointerDownHandler, IPointerUpHandler, IBeginDrag, etc out of the box
Got it... so that makes me think a singleton MonoBehaviour, right, and then I subscribe publicize events in there and subscribe in each component?
These interfaces you mention I see referenced commonly as it relates to UI elements, but I'm also primarily interested (for now) in the gameplay loop and its input handling
yes but you can use those events for in-game objects too
and when you do so, it interacts perfectly as you expect with UI (i.e. you cannot click through UI)
basically a singleton hodler for the instance that exposes the instance to the other components so they can subscribe or read the input however they see fit
Got it. I'll try investigating more down this path. I do generally like the idea of attaching controls via interface implementations and things "just work"
im working on isometric movement game, i setup an playermovement script using the default InputSystem_Actions but upon starting up the game the capsule doesnt move, i have no idea what to do now
pls someone respond 😭
Did you enable the asset?
E.g. inputActions.Enable()
yes i did
Anything in the console when you run the game?
You should add Debug Log statements too
alr imma try that and get back to you
looks like there's a problem here
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
which one is line 34?
maybe share the entire script in one of the websites listed there
is inputActions assigned?
pretty sure they r , i assigned them to unity default input system actions
Not the question
The inputActions variable itself
It's a code question
yes it is
Because from what I see rb is not assigned
That all seems right to me.. are you sure you don't have any extra copies of the script in the scene or something like that?
pretty sure i dont
or the input action c# file couldve been generated wrongly considering i also put the script in the scripts folder
just regenrated it and it still doesnt work :((
when i was moving in game and went back to scene the capsule moves and the camera locks to it
but in game nothing is happening its like a frozen window
turns out it was nvr a movement issue
it was a caemra issue
hi there
i tried to edit bindings of default UI action map, i wanted to add gamepad right stick to ScrollWheel action and remove it from Navigate action but for some reason when i do so Unity ignores changes so right stick keeps working as navigation and doesn't scroll, i also added LT and RT but it ignores it
i tried to restart Unity, reimport InputSystem asset and script but it didn't help
is this a problem with InputSystem or UI scripts?
have you added a Input System UI Input Module to your Event System?
yes
is it referencing an input action asset in the /Assets folder, i.e. outside the Packages folder?
i'm trying to figure out input prompts,
for them i'm using the GetBindingDisplayString() method (with default args) on the InputAction i need, which instead of returning the input for the current control scheme, however it instead returns both of them ("Q | Y" (button north on gamepad)), and i can't seem to find a way to get it to return the current control scheme
i'm wondering, is there a simple way to make it use the current control scheme or do i have to somehow do it manually?
this one inside Assets folder
.inputactions
i just checked does this file even changes when i edit it in Unity and yes, i found all bindings i added and made sure there's no right stick in Navigate and it is in ScrollWheel action, so i can say this is not InputSystem's fault
but there's another problem, each time i push the stick ot scrolls only once instead of scrolling continuously
how can i make it scroll continuously, like make it think that i push and release the stick very fast
Hi. I'm using Player Input to handle Xbox Controller Input. I'm having an issue where my code isn't being run if the Controller is connected after the scene is loaded. Is there a specific way I should handle this?
hi i am using playerinput in my fps game but i cant move the camera and also cant fire how do i fix it?
You need to provide details or it's hard to help you
Show your code, screenshots of your input action configurations, inspectors, etc
can you dm me i can show you anything you need on a call?
can you dm me i can show you anything
Hello, anyone else had issues when using both player input components and the event system ? My UI doesn't respond when there are player inputs in my scene. I found that disabling and enabling my event system at runtime and assin its action map again fix it but it's inconvenient.
https://discussions.unity.com/t/playerinput-component-is-causing-event-system-and-modules-to-not-function/943050/3 I found this post but i don't understand the soluce lol
so question.... what exactly is the Joystick input for vs Gamepad? do games really use this?
I am asking because I believe this is responsible for it moving in the top left direction for a character controller, cause it thinks it is moving but it really isn't
because I am noticing that when I remove the "Joystick" then it stops moving top left direction
and im not sure how AndroidJoyStick got in there, but GMMK 3 HE is my keyboard (which I also don't know how it got there)
"Stick [Joystick]" is a binding that includes multiple hardware inputs, namely the 2 things you see there, it isn't picking up your keyboard specifically
well GMMK 3 HE is the name of my keyboard, so what exactly could it be picking up?
I mean I guess I can just remove the Joystick controller type entirely and use KBM and Gamepad only and that fixes the issue of my character drifting.. but I'd rather also learn why
it isn't picking up your keyboard specifically, it just says that that type of keyboard happens to be included in "Stick [Joystick]"
any logical reasoning why this is causing my character to drift though?
*also not sure how AndroidJoystick is there either... but 🤷♂️ * (since the other Joystick binds says there is nothing binded for that specific map or whatever)
androidjoystick is just there because it's part of the "Stick [Joystick]" binding
it isn't specific to your project or your setup
that's just what "Stick [Joystick]" is defined as apparently
maybe check the input debugger
ah wait im mistaken somewhat; it's kinda the other way around in the case of the specific devices
your keyboard tells your os what it's able to do and unity picks up on that
From the input system perspective, everything that is not a Gamepad and that has at least one stick and one trigger control is considered a candidate for being a joystick.
Hello, anyone else had issues when using
Hi, I've generated C# class and this is how I set up my inputs but I'm not sure if I'm doing it the correct way. Should I switch back to Player Input and use events or what, any ideas? https://scriptbin.xyz/oyobuyowoy.cs
Use Scriptbin to share your code with others quickly and easily.
Having these input variables like this here is an antipattern in my opinion
managing a single instance of the PlayerInpuitActions object is good
but you shouldn't have this particular script do anything more than just manage and share that instance
thank you, let me see how I can make it better
Is this more like it? https://scriptbin.xyz/upehucuzal.cs
Use Scriptbin to share your code with others quickly and easily.
yes
let each individual script set up event subscriptions or just poll things in Update
basically let each script individually do whatever is best for that script
without an unecessary middleman which just adds busywork
Alright thank you so much, got it now
wrong channel?
hey can anyone help to make the player movement (first person) for android ?
(I think this is the correct channel to ask. Tell if i am wrong)
Thank you
have you tried googling for tutorials?
Working on the any key to skip scenes.
Wrote this for keyboard and gamepads:
public bool IsAnyButtonPressed() {
foreach(InputDevice Device in InputSystem.devices) {
foreach(InputControl Control in Device.allControls) {
if(Control is ButtonControl { wasPressedThisFrame: true } ButtonControl) {
return true;
}
}
}
return false;
}
How do I detect if the screen was touched?
So that it also works on devices with touch screens
Pretty sure you can use this instead of writing custom code:
Tldr; you can make a regular input action and bind it to all button controls with wildcards
hello I just switched to the new input system due to inconsistencies with the old system with controller binds
i still want to have a keyboard working, but it doesn't appear as an option
i don't have "keyboard" as a binding i can use.
it does appear in the input debugger though and I can select it when creating a new control scheme
im on macos and i have tried using version 2022.3.8f and 2022.3.62f
if you start typing "keyboard" or "space" or something, or press listen and hit a keyboard key, does it work?
i can't listen to keyboard presses and typing keyboard or space doesn't work unfortunately no
what about restarting the editor?
have tried already multiple times. i also upgraded the unity version to the newest
i can try again
what about input system version?
i got nothing
alright, thanks though
okay, after deleting the library, downgrading again using version control and deleting the input action and creating a new one it works somehow
Having some issues with Proton on Steam Deck. A user is reporting that an action I mapped to "button south", is mapped to the B key, which should be east.
No idea if other keys are off too, but I've mapped everything to be generic and tested on an Xbox pad.
I asked AI and it blamed Nintendo 🙂
what version of Unity and the input system are you on?
Unity 6.0, no idea what version of the input system.
I'll check when I get home
show the full version
Ah, I assumed you were at your computer and ready to debug the issue.
I remember there being some bugs with this kind of thing in the past, if you're on an old version of the input system it's possible you're on a version where it hasn't been fixed yet and you might be able to fix it by upgrading.
I hope it's that. Though I generally update packages when I update the engine and I'm on a fairly recent version.
Unity 6000.0.47f1 and 1.14 (latest)
Does anyone know what to do if UnityEngineInternal.Input.NativeInputSystem:NotifyBeforeUpdate returns value in addition to the Update from actionTriggered callback? Is this a normal behaviour?
Anybody know a quick and dirty way to get ALL input from a PlayerInput, not just mapped ones? For context as to what I'm trying to do, I have a multiplayer game and I'm trying to show all of a player's inputs on-screen, mapping to every button (especially on Keyboard) would be a pain in the butt.
Make an input action and bind it to */*
I recommend reading the "control paths" section here
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/Controls.html#control-paths
Thank you friend. :]
Sent a lil donation your way
Thank you!
☝️ Bumping the above.
If anyone has a game on Steam Deck and it works fine for them - that'd be helpful to know as well. Especially if it uses the same version (1.14.0) of the input system.
in android emulator, when i click on screen without releasing, i get both OnPointerDown and OnPointerUp events triggering . has this happened to you guys before? And the OnPointerDown triggers 2x too..
using UnityEngine;
using UnityEngine.EventSystems;
public class Card : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler, IBeginDragHandler, IDragHandler, IEndDragHandler, IArcLayoutable
switching display modes seems to cause a missing reference exception in this input system script? There's some code on substack that replaces it and makes it work but it seems like changing it isn't a good idea. Any suggestions?
its in InputSystemUIInputModule at line 476
Well your screenshot doesn't include line numbers so line 476 doesn't help much
But I'm going to mention that you are using the ? operator here with Unity objects which is a big nono
And often leads to precisely this kind of issue
should i just go ahead and change it? the editor gives me a warning and it doesnt seem too future proof
You should not use ? with Unity objects.
If you are doing that anywhere, you should change it
this aint my code bro its source code
Wdym by "source code"
its in the code for the event syustem
Ah
when i click the error it takes me here
Which line exactly has the error?
That's very unfortunate and seems like a bug in the input system
yeah
Are you on the latest version?
im a little behind 6000.022f1
but this is in the "2021 or newer" region so it looks ancient
More specifically I mean the input system version
for some reason my player1 input action maps are controlling both player1 AND player2? player2 works fine though?
public void OnMove(InputValue value)
{
// Read input from the new Input System
movementInput = value.Get<float>();
}```
btw a debug log Debug.Log("moved " + this); in onmove shows it's moving them both when onmove is called from player1
It's because they're using the same input device (the keyboard).
This is a bit of a special case, and using two action maps is not the preferred approach.
Check out the solutions in this thread: https://discussions.unity.com/t/multiple-players-on-keyboard-new-input-system/754028
how do i make it so holding up diagonal on my gamepad doesnt slow my player down? up really shouldnt do anything at all, just left and right for movement and holding down for crouching
Well for one you seem to have your Move action set as a Button action
It should be set as:
Action Type: Value
Control Type: Axis
but the reason "up diagonal" on your gamepad is slowing you down is simply because, for example "diagonal up/right" is just less "right" then simply holding all the way to the right.
As you can imagine, the point in red has a larger X value than the point in blue.
i see, what do i need to change so that it's either 1 or 0 then?
"normalize" the value you get by taking its Math.Sign
in your code you can just do like:
float axisValue = ctx.ReadValue<float>();
if (axisValue != 0) axisValue = Mathf.Sign(axisValue);```
if you use Math you don't need to check for 0 since Math.Sign handles 0 correctly
or if you're using SendMessages:
void OnMove(InputValue iVal) {
float axisValue = iVal.ReadValue<float>();
if (axisValue != 0) axisValue = Mathf.Sign(axisValue);
}```
why doesn't Mathf.Sign handle 0 anyways
who knows
also - for joysticks you don't need to do a 1D composite axis with left/right. You can just bind it directly to Left Stick/x [Gamepad]
sgn is supposed to
a ton of Mathf methods delegate to Math anyways, and the ones that don't but have equivalents have the same behaviour
this is just... a weird outlier, i guess
working now, thank you all for the explanation and help!
hmm one more issue, my jump (action type Button), is pretty inconsistent with the gamepad. sometimes the character jumps and other times not. no issues when using keyboard controls. in my HandleInput function (called in update), the debug is firing every time that jump is pressed but the character doesnt always actually jump. any ideas why its behaving like this?
inputJump = playerInput.actions["Jump"].WasPressedThisFrame();
if (inputJump)
{
Debug.Log("Jump pressed");
}
is this code in Update, or FixedUpdate?
Also where and how does the inputJump variable get used?
If inputJump gets used in FixedUpdate, that's your issue. You can fix it by changing to this:
if (playerInput.actions["Jump"].WasPressedThisFrame()) {
inputJump = true;
}```
or:
inputJump |= playerInput.actions["Jump"].WasPressedThisFrame();
HandleInput is in update, HandleMovement is in fixed update. the block of code i showed is in update
the issue is that Update runs much more frequently than FixedUpdate
so you might get the true one frame, then it becomes false the next frame, then FixedUpdate runs, never having seen the one true frame
hmm, why dont i see the inconsistency with keyboard controls and only gamepad though?
probably just by chance
idk tbh, you should definitely see it with both
but try my fix, see if it helps
oh also
you will need to do inputJump = false; in FixedUpdate after the jump code.
otherwise it will get stuck to true forever 😛
think of it as "consuming" the intent of the player to jump.
yeah this seems much better now, thank you again
this is painful to hear but i know it to be true
(my mind still considers 30fps normal)
Can someone explain to me how I use this component with "Invoke C Sharp Events" selected?
It's the most misunderstood thing in all of Input System
When you have it set to "Invoke C Sharp Events", what you're supposed to do is subscribe to this event and handle all input through it:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/api/UnityEngine.InputSystem.PlayerInput.html#UnityEngine_InputSystem_PlayerInput_onActionTriggered
Basically - I don't think it's what you want.
These 4 events will be triggered
because I've never seen anyone use onActionTriggered
well I'd like to use c# events instead of unity events, but I want to support local co-op without any extra work on my end.
So what you can do is set it to Invoke C# events basically as a "do nothing" mode, and then you can manually subscribe to the actions assert from the PI
private void OnEnable()
{
var playerInput = GetComponent<PlayerInput>();
var actionMap = playerInput.actions.FindActionMap(_settings.inputActionMapName);
var action = actionMap.FindAction(_settings.movementActionName);
action.performed += PlayerInputOnonActionTriggered;
}
for example:
PlayerInput playerInput;
void Awake() {
playerInput = GetComponent<PlayerInput>();
InputActionAsset asset = playerInput.actions;
InputAction moveAction = asset["Player/Move"];
moveAction.performed += MoveHandler;
}
void Movehandler(InputAction.CallbackContext ctx) {
// handle input here
}```
for example
yeah
I just want to point out that you can do this no matter what setting you have for the behaviour field on the PlayerInput component
"Invoke C Sharp Events" just enables onActionTriggered
you're basically bypassing the PlayerInput component like this. There's still a benefit because you get the PlayerInputManager device handling stuff out of it
ah okay. Will this work with multiple instances of PlayerInput for local co op?
yep
ah
yea that's the main benifit I want. I feel that the PlayerInput component is almost useless lol
agreed
the tutorial I'm following's input system thing has an action folder in action properties but in my version it's not there
do I need to worry about this and what should I do instead?
I want to add movement
Both have an Actions section, wdym?
on the right but nvm I found another way
In your screenshot on the left you have a Binding selected
not an action, @charred swallow
Is it recommended to always have active input handling set to both? It seems like every "new input system" tutorial i find doesn't work unless I set the active input handling to both in project settings -> player
it's not recommended but it's not bad
Most projects just use the new system alone.
if you have to set it to both then sounds like you're also using the old input system though
I was doing a CodeMonkey tutorial that was 3 years old so maybe that was the problem but my ball wouldn't jump until I set it to both. Maybe the tutorial is too old maybe:
https://www.youtube.com/watch?v=Yjee_e4fICc
✅ Get the FULL course here at 80% OFF!! 🌍 https://unitycodemonkey.com/courseultimateoverview.php
👍 Learn how to make BETTER games FASTER by using all the Unity Tools and Features at your disposal!
👇
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish....
did you have errors? what did you have it set to before?
There weren't any errors in the console and it was only set to the new system before. I then changed it to use both without making any other changes and it started working. This was my code and the sphere gameobject had the needed components like rigidbody and player input assigned. The properies for playerinput was also assigned to how it was in the video. Code:
using UnityEngine.InputSystem;
public class TestingInputSystem : MonoBehaviour
{
private Rigidbody sphereRigidbody;
private void Awake()
{
sphereRigidbody = GetComponent<Rigidbody>();
}
public void Jump(InputAction.CallbackContext context)
{
Debug.Log("Jump" + context.phase);
sphereRigidbody.AddForce(Vector3.up * 5f, ForceMode.Impulse);
}
}```
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
ok, what if you set it back to "new" only now?
Just changed it and waiting for project to load back up. Picture of my components:
I should have expanded the events section
oh, it worked on the new input system...is that normal to have to switch the active input whenever you make changes to the input system?
Also I think the jump only works if I select my sphere before entering play mode
No it's not normal
Thank you for all the help! I'll take another crack at it tomorrow morning. Honestly I should probably look into some unity C# videos before using C# to program these input actions. I feel like every time I see private or public void awake, start, update, OnDestroy I get super tripped up so maybe I'm skipping a step here
perhaps check out the resources pinned in #💻┃code-beginner
could skip parts you already know but at least go through it to make sure you aren't missing anything
Will check it out! There is that junior pathway I see in there I haven't completed yet so that might be a good thing to tackle this week before moving on to input actions
Epic movment scripts uning input system
How would I go about having it where it just checks if the player pressed anything?
I was trying to make a QTE system, so I have a scriptable object holding the QTE options with their images and whatever the player is supposed to press, and I want to check if the player presses anything. And whatever they press, I save it as a string, and check it against the string in the scriptable object. If it matches, they go to the next, and if its not, they fail.
perhaps this is it?
Im studying how to be more modular when coding. Is it a good practice to make ScriptableObjects that only has an InputActionReference for Inputs?
so if my player has a LEFT and RIGHT movement I make 2 public variables of that ScriptableObject for left and right and then drag N drop specific keys in. Is this a good/clean way of doing it?
For what purpose? You're adding a layer of abstraction/indirection here. That can be useful but only when there's a reason for it.
Im doing a service-locator pattern. I dont really want to try and get or pass Specific InputActions using strings (because fragile). So im stumped as to any idea how to go about it in a professional way
thanks for the input tho you have a good point it would be bad design to do it for every Input without reason
Well I never would have suggested strings as an alternative. I'm more talking about - keep things closer to the metal. Put the IARs in the scripts that actually need them directly, instead of introducing a middleman, unless you have a strong reason to introduce a middleman
oh... alright sounds good let me try this. Thanks. Maybe I was overthinking it
hey, after upgrading to Unity 6, the scrolling logic is completley messed up. Mac OS scrolling is ridiculously fast, and other platforms are also way faster than they were before.
Was there any change to the values being reported by pointers?
I’ve found that sometimes project settings get messed up too after updates, so worth checking any related values
don't see any values here relating to scrolling?
wait, is it this?
i tried everything but i am not able to get the default jump input action button in the cancelled phase
- i tried setting it press and released interaction type
- i tried the hold type
but what it does is it directly goes into waiting phase
also how are you receiving the input?
I am new to unity so i might be doing it wrong i tried reading the new input system docs and this is where i end up
using UnityEngine;
using UnityEngine.InputSystem;
public class Jump : MonoBehaviour
{
[Header("Ground Sensor Property")]
public Transform sensorPosition;
public Vector2 sensorSize;
public GameObject sensorPrefab;
public LayerMask GroundLayer;
[Header("Jump Properties")]
public GameObject mainObject;
public float jumpForce = 10f;
private Rigidbody2D body;
private InputAction jumpAction;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
body = mainObject.GetComponent<Rigidbody2D>();
jumpAction = InputSystem.actions.FindAction("Jump");
}
// Update is called once per frame
void Update()
{
PlayerJump();
Debug.Log(jumpAction.phase);
}
public void PlayerJump() {
if(jumpAction.phase == InputActionPhase.Performed)
{
body.linearVelocityY = jumpForce;
}
if(jumpAction.phase == InputActionPhase.Canceled)
{
body.linearVelocityY = body.linearVelocityY*0.5f;
}
}
public bool isOnFloor()
{
if (Physics2D.OverlapBox(sensorPosition.position, sensorSize, 0f, GroundLayer))
{
return true;
}
else
{
return false;
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.white;
Gizmos.DrawWireCube(sensorPosition.position, sensorSize);
}
}```
don't you have to Enable the action with that setup?
it is enabled by default it work the jumping part but not the canceled part
were the falling is cancelled mid air and enables the variable jump height
if(jumpAction.WasReleasedThisFrame())
{
body.linearVelocityY = body.linearVelocityY*0.5f;
}```
this fixed my problem
does the input system work with ninteno switch pro controllers? in the input debugger i get all my inputs but in play mode it just doesnt read the inputs? i saw forum and redddit posts about this but didnt find anyy solution
this is the code i have in Update() to read joyystick inputs:
throttleInput = controls.Gameplay.Throttle.ReadValue<Vector2>().y;
steerInput = controls.Gameplay.Steering.ReadValue<Vector2>().x;
inputsystem setup
ive tried with steam open and closed, still not getting inputs in playmode either way
ive also tried both wired and wireless
Show your full code
sure, one sec
public class Car : MonoBehaviour
{
PlayerControls controls;
[Header("Inputs")]
public float steerInput;
public float throttleInput;
void Awake()
{
controls = new PlayerControls();
// controls.Gameplay.Throttle.performed += ctx => throttleInput = ctx.ReadValue<Vector2>().y;
// controls.Gameplay.Steering.performed += ctx => steerInput = ctx.ReadValue<Vector2>().x;
}
void Update()
{
// old input system
// steerInput = Input.GetAxis("Horizontal");
// throttleInput = Input.GetAxis("Vertical");
throttleInput = controls.Gameplay.Throttle.ReadValue<Vector2>().y;
steerInput = controls.Gameplay.Steering.ReadValue<Vector2>().x;
// Debug.Log(controls.Gameplay.Throttle.ReadValue<Vector2>());
}
}
omitted the steering and phhysics code, ive already confirmed thhat works fine with keyboard inputs.
but i can add that too if you want
i have inspector to show the inputs, which showed correctly for myy old input system with keyboard inputs. but now they dont change at all during playmode usingh my controller

Yo anyone there??
I'm looking for a simple way to create local multiplayer with multiple player prefabs
Ping me if u can help
after testing a lot of solutions (like using screen size) i still cannot find a correct way to scale touch delta so the movement speed is the same on all devices
Plz help
You never enabled your PlayerControls instance
have you tried googling for it
oh youre right… 

all working now

Hey All, I've trying to make a new action map from scratch to learn it all better but am having issues with my mouse movement. I'm trying to set up my Look-Around Action so the player can use there mouse to look around. Right now, when I enter play mode, the camera just spins really fast and moves when I don't move my mouse. Is this how the Action should be set up for mouse?
If this looks right I could share what my code looks like
We would need to see the code
In order to get input from an ESP32 joystick to Unity, is it XInputController system?
How can I clear any pending Input events?
After respawn, my player is reading the last input for movement and resumes that movement once alive again. I've programmatically reset all animations and velocity on death, so the only explanation is a pending input in the input system queue.
For the most part, do y'all generaly use Invoke Unity Events when setting up controls for your games?
I use different things depending on the game.
For the most part I try to avoid PlayerInput except when making a local multiplayer game though.
i don't remember the input system having a built-in queue, stuff doesn't really wait to be consumed
could you show your !code?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
What makes you want to avoid player input on local multiplayer?
Also does anyone know of a good resource that covers 3d movement with the new input system. I've scoured the unity 6 documentation and random videos on youtube but not finding a simple way to just implement jump and wasd. Maybe there is a script out there that I can reference?
You can simply use this in code, no setup of input system needed...
using UnityEngine.InputSystem;
Keyboard keyboard = Keyboard.current;
if (keyboard!=null) {
if (keyboard.wKey.isPressed) walk forward;
}```
There is also Mouse.current, and Gamepad.current.
This wasn't towards my question was it?
I don't avoid PI on local multiplayer
That's the only time I use it
Well I read simple move with wasd.
Sorry misread, do you do the new input system with pass through for actions on local multiplayer?
I rarely use pass through actions, but there are cases for it
Honestly the answer to these questions is all "sometimes, if the circumstances call for it"
You need to ask yourself what your goals here are. Are you making a polished game you wish to release and maintain? Is it a hackathon or throwaway project?
There are many tutorials out there for various types of game movement using input system
Maybe I'm making it more complicated than it needs to. I generated a default action map and made a DiscordTest script with the code you provided. I also added the player input component to the player and made the behavior invoke unity events. Should I put your code in a fixedupdate?
statements have to exist in some method, constructor, accessor, initialization body
they can't exist directly in a class
It is for Update like all input.
eh, some input can be done outside of that