#🖱️┃input-system
1 messages · Page 15 of 1
why dont you just name them to what you want them to be used for?
you can always rebind them
its less in the long run
ok lol
used to be kingtempest07
oh thats my internal name
i guess it just didnt display my display name
but yeah, you should probably just name them things like "jump" or "movement"
I feel like that just complicates things
not really
also that wouldnt fix my keyboard problerm would it?
it makes it so that you can change bindings at any time via script
probably not, but i think it would be a good idea
idk maybe i misunderstand it
Essentially the whole appeal of it is that you can just say "Movement.ReadValue<Vector2>()" and get the direction
also, starting from basics - is it enabled? I needed to manually enable it before it accepted keyboard input
it doesn't mattrer if its using dpad, left stick, wasd or anything really
sorry for long response, I was AFK for a moment
are you talking to me?
if so then i dont see a way to disable it so I assume its enabled lol
in code I mean
yeah it works when I have the controller off when I start the game
crude testing code but something like this
but its weird because the enter key works either way
I think It just needs to accept both keyboard and controller at once but it doesnt like that
I know the keyboard can control it the problem is why it wont swap between keyboard and controller
is what weve narrowed it down to
thats why i think it could be due to control schemes not being separate
thats the whole point of having them is to switch between them when one is being used
but they keyboard would still be bound with the controller
so i dont see how its different i personally like it this way, dont want to turn down help but I dont see how this could fix it
So yeah if anyone else knows how to help, heres the tldr. My input doesnt accept controls from controller and keyboard at the same time, online from what ive read it is supposed to do so. They are under the same actionmap and keyboard only works when controller is off from the start of the game. (ty guys for trying to help so far)
can I change these flags somewhere, the keyboards flags are different and while im not sure exactly what they all mean they seem like they would affect this.
Any ideas why simulated touch input from mouse or pen doesn't work?
Function is not executed when mouse clicking.
inputSystem.Camera.TouchPress.started += ctx => StartTouch(ctx);
I have it Enabled in OnEnable
show the rest of the code and the action/binding?
Show the configuration of the action and the binding (right side of the Window) as well as your actual movement code
That's just the up part. show the composite binding itself
The thing that says 2D vector
Can you try without it being normalized
anyone know why this isnt moving my character?
https://hastebin.com/share/siwubisatu.csharp
https://hastebin.com/share/ixisawawol.csharp
It works now, there were some weird issues that I cant explain, but after redoing it, it works.(Maybe I needed to change build to Android in settings)
I have been looking around and I have not found details on how to add touch for controller buttons. For Example, PS5 or VR controllers that sense touch before the trigger is pulled. Can anyone give me directions or a link on how button touch is done in the action Input system?
Found it it's nested in the little side arrow under the path dropdown for the binding properties.
Is there a way to bind keys to to a value action? So for example keys 0-9 will set their respective values in their action when clicked?
I ended up adding a scale processor to each key corresponding with it's number
How to disable/ignore Input system event when interacting with UI slider?
Currently when I move the slider, other interactions are still happening.
Even better if I could somehow specify which UI elements are ignored by the input system.
How do others do this?
https://stackoverflow.com/questions/70636241/unity3d-new-input-system-is-it-really-so-hard-to-stop-ui-clickthroughs-or-figu
Seems like this is a problem others have as well.
pointerOverUI = EventSystem.current.IsPointerOverGameObject();
I was able to use this.
I check if a pointer is on top of the UI on context.started.
Going to test it on touch screen.
I have two Player Inputs, and it seems like the second one uses both of my gamepads regardless of what i do. Im trying to make it so each of the two has one gamepad each. I’ve looked everywhere for a solution but I couldn’t find what I was looking for.
You need to use PlayerInputManager to spawn the players
Anything i need to about the way they’re spawned in? I already have a code that spawns them in, would it work if i just swapped the line of code that does it out?
is there a workaround to support multiple keyboards for the input system?
Try adding a normalize processor to rotation. Ive never done mouse movement so its just a guess though
delete the 2D vector binding
bind directly to Delta [Mouse]
do not apply any processors
also make sure your code is in Update not FixedUpdate
i cant build my game
i get this error all the time
upgrade your packages to the latest versions and try deleting your library folder
now this error
how can i join a player without instantiating a new object?
public void OnMove(InputValue value) { _moveVector = value.Get<Vector2>(); Debug.Log(_moveVector); }
I have this script on the same game object as the player input component, but it doesn't seem to be sending messages. What am i doing wrong?
I'm not seeing the debug message when using any of the keys i have bound to the Move action
Opening the input debugger from this component, it shows "StarterAssets.inputsettings.asset" rather than the asset currently assigned to the component. Is this normal?
that's the settings asset, not the input actions asset
you'd have to show your script
sorry for the pastecode link. As far as i know, the OnMove function should at least be printing the debug message. When I switch the Action field on the player input component to the default action map, the OnMove function is called.
show how you nset up the Move action and bindings
i have two control schemes, and ticked the box for each binding
can you stry explicitly selecting a control scheme
Do you mean by setting the Default Scheme from <Any> to KeyboardMouse? I'll try that now
yes
Does the Input System not recognize joycons? Most of my other controllers are detected right away but I try hitting buttons on a paired joycon and get nothing
I can't find any way on how to rebind the controls via script. How can I do this?
I have a player controller with serialized input actions
how do they get the playerInput.actions? is the playerInput not an InputAction?
{
playerControls.ChangeBinding(0)
.WithPath("<Keyboard>/enter");
}```
playerControls is an InputAction
This is throwing me a bunch of exceptions
I've set up a pointer/touch drag event in the input system, but I also have a UI slider. The main drag event is firing as well as the slider when I use the slider. Is there a way to get the slider to consume the pointer events?
the way I've set it up is with a custom InputActionAsset handling screen drag globally, but the EventSystem is using DefaultInputActions stuff, so I guess they just ignore each other?
I can probably fix this by just not having a slider and using two buttons instead, but it'd be nice to know what the right way to set it up would have been
I guess what I need to do is to get my global screen drag to run off of the in-scene EventSystem component? is eventData.Use() the right way to consume the input in that case? I assume pre-built things like slider components will do that automatically. which has me wondering if there's a priority system to make my global drag the last item to get the event.
I have this trange issue, where any / all new inputs I create, are disabled by default?
Any easy way to fix this?
How did you create them? Generally if you're using the generated input wrapper class you need to call .Enable() on it before use
I just created them through the standard GUI:
sure but how did you hook it up to your code?
Through UnityEvents/ActionCallbacks.
that's quite vague
Are we talking about the PlayerInput component?
Manually referencing the input actions asset?
Something else?
The PlayerInput Component specifically.
I am struggling with something with the buttons when you choose in the game, like when you press on Player 1, only one player appears and when you press Player 2, 2 players appears, and it works fine but right now when I press on Player 1, 2 players appear, how can I fix that?
anyone have the answer?
You need to attempt to debug yourself first. Log what's happening and in which order. https://unity.huh.how/programming/debugging
I don't know coding much
This discord is not a debugging tool, you need to learn how to do that yourself.
I don't know where I can debugging
Luckily I provided you with a link explaining how different debugging methods work.
Hey so I'm newish and I'm trying to use the newer input system in unity to support local multiplayer. Does anyone know how to use essentially assign a gamepad to an object when you instantiate it?
Use PlayerInputManager
can some one point me in the right direction with new input system of how to use joystick and mouse to rotate an object around a polayer in 2d ii want the rotation to be in line with the mouse cursor or where the joystick points
Not really related to input system. Take position of your pointer, subtract position of the player to get direction, rotate the object to that direction.
will this work for joystick though,
im not really striggling iwth mouse pointer i just cant seem to use the vector two of a joystick to rotate the object around the player
if you use joystick directly, it is already your direction vector, if you move the pointer, the point is the same as mouse pointer
if joystick is too sensitive to get smooth direction you want to smooth rotation to not be instant.
thank u i will try this, never done controller inputs at all so im struggling a lil 😅
I've binded 2 keys on that event : 1 and 2
When I click on 1, 1 is debugged
but when I click on 2, it is still 1 who is debugged
is there a way to get the value of the actual pressed binded key ?
public void OnSwitchWeapon(InputValue value){
Debug.Log(value.Get());
}```
how would I get the current/latest input from any device?
lol I had no luck with this last night. It only works well if you're using 2 different types of controllers or like a keyboard and a gamepad. I think I kinda figured it out without using any of the prebuilt stuff though. Thanks anyway : )
Is there a way to influence one input with another?
I have shift as a walk button
I got this
When I hold WASD vertical reaches 1
Is there a way to limit it to 0.5 when I hold shift?
I'll check tomorrow because it's almost 12 am
But thanks anyway I'll see what I can do
how would I convert an InputControl to an InputControl<TValue>?
What are you trying to do?
hello, is it possible to call the action in the button from the level of script. i.e. I don't physically press the button but the inputmemager will think it is pressed.
Is it possible to get PlayerInput from a button click?
I'm currently using a hackjob way of getting the currentInputModule from PointerEventData and then fetch It's gameobject's name (which I have renamed to the corresponding playerIndex)
I'm getting the path of any input using onAnyButtonPress before rebinding, but I also wanna use it's value to determine if it should actually be set or not
like if it was inputting before the rebind button was pressed so I know to filter it out because of an issue with the gamecube controller adapter (a controller I'd want to support)
so ideally I'd use ReadValueFromPreviousFrame but I can't with the standard InputControl class
how do i check the action type of an input action via code?
do i just
Debug.Log(actionName.ActionType.ToString());?
wait its expectedControlType right?
Hello, how can I find out which key was pressed ?
Very vague question
You're basically asking "how does input handling work"?
maybe explain what you're trying to do and explain your specific problem and what you've tried so far.
for controller joysticks, what should i set the deadzone too? im hovering around 0.03 but still getting a bit of drift (my controller is not drifting)
0.03 is really low i would do something more like 0.15-0.2
Depends on ur game though is it 3d?
I guess the more pertinent question is how much nuance does your movement need?
I mean you would know best what your contoller deadzone needs
https://www.youtube.com/watch?v=HmXU4dZbaMw I was using this tutorial to set up my new input system. When I got to the 2:17 mark, I have a different menu to him for the external tools, and I also get the syntax error for Using UnityEngine.Input. How can I make it so Registry packages have affect in scripts, like what he did by clicking the checkbox.
The "new" Input System in Unity still doesn't come pre-packaged and is complicated to understand at a glance. It's no surprise new game developers don't know where to look in the engine to find it, or how to use it.
In this tutorial, learn how a beginner can adapt their current project to use the new input system in a simple way, as well as usi...
I am using unity version 2021.3.5f
Hey! I'm also a beginner - but maybe it will help. When I was setting new Input System, after installing the package : Edit -> Project Settings -> Player -> Other Settings -> under ``Active Input Handlingyou can pick old / new OR both input systems ->restart Editor. It worked for me, without changing anything in theExternal Tools. I'm using2022` Unity version but maybe you can try this before someone more advanced will reply
Yeah I have done this. I think the package will work regardless weather I do this other thing but I am not sure. not many other tutorials mention it
Also I used https://gamedevbeginner.com/input-in-unity-made-easy-complete-guide-to-the-new-system/ to learn about the new system
So i have this problem with the input system. I am making this 2D platformer learning project. The problem is the player moves and jumps when in the editor, but only jump works when i make a build. Should i post the code i’m using? I am using the generated C# class, so i enabled the input action in OnEnable() and create a new instance of the class and subscribed to move and jump actions in Awake()
I'm trying to get input system working in my project, and I currently have something like what's on the screenshot below. I reference both Movement (Vector3) and Rotation (axis) with Input Action References in my script, and I'm trying to get the values in my script like this
_moveAction.action.ReadValue<Vector3>();
but it is always Vector3.zero. Input debugger shows the keys on the keyboard being pressed properly. Does anyone know what's going on?
I have the new input system selected in player settings already, and I added keyboard and mouse as supported devices
what's weirder, Keyboard.current.aKey.isPressed reacts properly
what if you do cs void OnEnable() { _moveAction.action.Enable(); }
Why would it be disabled...?
I'll try that in a sec
well it does work
but why was it disabled in the first place?
it's not enabled by default
is there a way to enable them through the inspector maybe?
If you dont want to enable them youll have to use the player input component method.
hi there
quick question, is there a way to use InputValues with button actions? I'm trying to implement a simple jump action but the InputValue doesnt fire a "released"/"cancelled" event when I'm letting go of the button
you should get one callback upom pressing it and one upon release
hm, I only get one per press
and can use myInputValue.isPressed to distinguish
that being said I'd recommend switching to unity events
so you get a full InputAction.CallbackContext
I thought so as well, but curious if this is a solveable problem without that change, cuz otherwise the functionality is kinda useless
I'm using PlayerInput btw to invoke messages for my script
I'm aware
that's the only context in which people deal with InputValue
My understanding was that you get two calls - but I also long ago abandoned that mode of operation precisely because InputValue is so useless
make sure you don't have any interactions on your action or binding
hm, thats a shame, but I guess I'm gonna switch back to UnityEvents
Whatgs the proper method for doing 2 player local multiplayer input handling, I am trying to use the player input system and I am not sure if I need to just restart
using PlayerInputManager
Progress! not much but I guess I am on the right track
how do I get a true or false if a button is being held or pressed with the new input sytem and invoke unity events?
Please do not cross-post. It would have been better if you only posted here.
🤓
Heyas. So how do we properly track mouse movement? I've got it set to click and drag an object, reading a Vector2 from Position [Pointer], remembering the offset between the mouse and the object when it's clicked, and moving it in relation to where the mouse moves. It works, but the location value of the mouse is much bigger than expected and the object moves much too far with each mouse movement. It seems like the location of the mouse is not using the same positioning system as the objects in the game space? Maybe it's in relation to the whole screen?
post code how you are measuring it
// Main
void OnMove(InputValue value)
{
if (!(heldTile is null))
{
heldTile.moveTo(value.Get<Vector2>());
}
}
// Tile
public void moveTo(Vector2 location)
{
if (heldOffset == Vector2.zero)
{
heldOffset = (Vector2)transform.position - location;
}
else
{
transform.position = (Vector3)(heldOffset + location);
Debug.Log(heldOffset + " " + location);
}
}
!code and describe what exactly you want to achieve
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Cool, edited it. The Tile object is supposed to move with the mouse when a button is held.
are you trying to animate it every step of the way following pointer, or just attach to it?
Not sure what you mean
is the tile have to move along the valid grid placements or just freely dragged
Not sure what you are doing there. But to get offset you just have to cache coordinates of the Input.mousePosition when it was first pressed and then just compare with current one
Or rather extract it from new input system setup action instead of Input.mousePosition
Freely dragged, yeah.
That's what I've done here.
So just dragging is easy, attach it to mouse position.
To debug pointer position you might want to setup a UI element to show the coordinates real time
Using debug gizmos would help to visualize the problem as well
cool, I'll look into that
You also don't show how you detecting drag events, Selectable interface has dedicated ones for that. Also EventSystem has drag threshold it can factor in in getting exact start drag point
Oh nice! Thanks
heyo
I am rewriting my old script to adapt the new input system and I wanted to know how can I replicate this
else shooting = Input.GetKeyDown(KeyCode.Mouse0); ```
I was able to completely rewrite my character controler but this smol area have got me thinking
I guess this went unseen x)
I'm replying to myself in hopes of someone seeing it.
also, this is the code for the player
https://gist.github.com/abdouxbn/e099f8866d759a8d82db82ba2cf8cabd
P.S.: I tried subscribing to the performed state in Awake()
read the value directly in Update() and in FixedUpdate()
Subscribed to the ReadInput() function and passed the Callback context
even tried subscribing to DoMovement()
nothing seems to work when making a build, except the jump!
Respected, I am trying to rotate the camera around a car when the user touches the screen, and when the user touches the car, then not rotate the camera, but I am not able to achieve my goal. My car layer is "Car". And the other layer is "Default". Anybody can help me in this regard? Please.
void Update()
{
if (Input.touchCount > 0 || Input.GetMouseButton(0))
{
#if !UNITY_EDITOR
ray = sceneCamera.ScreenPointToRay(Input.touches[0].position);
#endif
#if UNITY_EDITOR
ray = sceneCamera.ScreenPointToRay(Input.mousePosition);
#endif
if (Physics.Raycast(ray, out var hitInfo, Mathf.Infinity, ~whatIsCar))
{
Debug.DrawRay(transform.position, hitInfo.point, Color.red, 5f);
Debug.Log(hitInfo.collider.gameObject.layer);
// touch = Input.GetTouch(0);
// float mouseX = touch.deltaPosition.x * Time.deltaTime * _mouseSensitivity * -1;
// float mouseY = touch.deltaPosition.y * Time.deltaTime * _mouseSensitivity;
float mouseX = Input.mousePosition.x * Time.deltaTime * _mouseSensitivity * -1;
float mouseY = Input.mousePosition.y * Time.deltaTime * _mouseSensitivity;
_rotationY += mouseX;
_rotationX += mouseY;
_rotationX = Mathf.Clamp(_rotationX, _rotationYMinMax.x, _rotationYMinMax.y);
Vector3 nextRotation = new Vector3(_rotationX, _rotationY);
_currentRotation = Vector3.SmoothDamp(_currentRotation, nextRotation, ref _smoothVelocity, _smoothTime);
transform.localEulerAngles = _currentRotation;
transform.position = _target.position - transform.forward * _distanceFromTarget; } } }
do anyone know how to use player input manager like joining manually
Can someone help me please? I kinda lost
Nobody can help unless your ask your question
Forgot to @
MissingMethodException: Method 'Player1Movement.OnJump' not found.
System.RuntimeType.InvokeMember (System.String name, System.Reflection.BindingFlags bindingFlags, System.Reflection.Binder binder, System.Object target, System.Object[] providedArgs,
using UnityEngine;
using UnityEngine.InputSystem;
public class Player1Movement : MonoBehaviour
{
// assign the actions asset to this field in the inspector:
public InputActionAsset actions;
public float speed;
public float jPower;
[SerializeField] Rigidbody2D rbody;
public float JumpCooldown;
// private field to store move action reference
private InputAction moveAction;
void Awake()
{
// find the "move" action, and keep the reference to it, for use in Update
moveAction = actions.FindActionMap("Player").FindAction("Move");
// for the "jump" action, we add a callback method for when it is performed
actions.FindActionMap("Player").FindAction("Jump").performed += OnJump;
}
void Update()
{
// our update loop polls the "move" action value each frame
Vector2 moveVector = moveAction.ReadValue<Vector2>();
rbody.velocity = moveVector * speed;
}
private void OnJump(InputAction.CallbackContext context)
{
rbody.velocity = Vector2.up * jPower;
// this is the "jump" action callback method
Debug.Log("Jump!");
}
void OnEnable()
{
actions.FindActionMap("Player").Enable();
}
void OnDisable()
{
actions.FindActionMap("Player").Disable();
}
}
I read on the fourms about some bug forcing you to need a workout, not sure if its that or if I just messed something up, left and right work just fine and the debug command does go thru when pressing jump so idk whats happening here
Are you trying to invoke a private method from outside?
Nope, legit just using the new input manager thing to invoke stuff
My only script is above
examine the exact line where the error originates
If the debug shows up before its only happening at the closing brackets? so wth is happening here
Not using find methods should remove some confusion. Make direct references then you'll know what object is used exactly and what it has
Debug.Log also has context parameter, use it to find what object used exactly
Debug everything in the chain
This is the only line of code able to invoke OnJump, and its in the same file
actions.FindActionMap("Player").FindAction("Jump").performed += OnJump;
let me comment out some stuff and see if that changes anything
Nope still happens with just a debug log, so its got to be an issue with OnJump(InputAction.CallbackContext context) or a Unity Issue
Right, OnJump requires context and you are not providing anything. So it is treated as entirely different method
And you don't have parameterless OnJump()
So do I just delete InputAction.CallbackContext context)
from the ()
do you need that context? Does action provide that context?
Well I removed it and got a compiler error, so I guess its needed, sorry about this, I haven't used unity for like 2 months so I am a little rusty
.performed += (context) => OnJump(context);
If I'm not mistaken
Same thing as before, it works, the debug is called, but for some reason it doesnt run the line before the debug... I am wondering if its a bug...
make sure it's the correct parameter type
it could output anything you set it up to output
Again. If the parameter is incorrect then it is treated as completely different method
Wait is this my problem
look at the specific action what it outputs
evidently it happens on both
I think its the same issue as this post, which means this is a unity bug or poor design https://forum.unity.com/threads/missingmethodexception-method-not-found.1337873/
You can find tutorials pinned in this channel how to use actions properly. The package also has example project.
I ripped my base code from the documentation-
If you're using sendmessages, jt uses InputValue, not CallbackContext
The latter is for "Invoke Unity Events"
Should I be using sendmessages?
So I change it to?
Are you going to use messages?
The change all the CallbackContexts to InputValue
If events, just change it and you seem to already be set?
I didn't look at your code though, just the most recent messages
Well it seems to have fixed the error but my jumping still doesn't work 😭
rbody.velocity = Vector2.up * jPower; Should have worked tho
The action is named EXACTLY Jump? The action map is named EXACTLY Player? Capitalization included
Do you get the "Jump!" Debug?
I do, well I did, I changed it to debug(context) but its still being ran either way
Ok yeah, I see that debug
ignore the player 2 action maps
Can you click Jump and show that same picture again?
Did you do this?
#🖱️┃input-system message
yes
UnityEngine.Debug:Log (object)
Player1Movement:OnJump (UnityEngine.InputSystem.InputAction/CallbackContext) (at Assets/Player1Movement.cs:37)
Player1Movement:<Awake>b__6_0 (UnityEngine.InputSystem.InputAction/CallbackContext) (at Assets/Player1Movement.cs:22)
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)
I dunno then. Maybe someone else will have some insight, sorry
I'm wanting to change the scaling factors on the "Look" action at runtime:
GPT-4 suggested this approach, however it doesn't work and I can't help feeling there must be a better way
int sensitivity = int.Parse(GetCurrentLabel());
InputAction look = GlobalControl.Instance.trrControls.Vehicle.Look;
Debug.Log(look.processors);
// Find the binding index for the action you want to modify
var bindingIndex = look.bindings.IndexOf(b => b.action == "Look");
if (bindingIndex >= 0)
{
var binding = look.bindings[bindingIndex];
binding.processors = $"NormalizeVector2,ScaleVector2(x={sensitivity},y={sensitivity})";
look.ChangeBinding(bindingIndex).To(binding);
}
else
{
Debug.LogError("Binding index not found");
}
Debug.Log(look.processors);
why not just handle it in your input handling code?
wouldn't it be much simpler?
Yeah you’re right
Why is it that in Unity, I can only move the PC forwards by squeezing the SD or AS keys down, not just the S key? Here's my code, I'm not sure why this is the case.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class walk : MonoBehaviour
{
Rigidbody2D rb;
static float walkSpeed = 3f;
static float runSpeed = 5f;
float inputHorizontal;
float inputVertical;
Vector2 playerPosition = new Vector2(10f, -1.5f);
public bool isWalkingOnYVector = false;
static float mySpeed;
public Animator tristanimator;
//Controls all his anims
//private float stamina = 100f;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
tristanimator.SetFloat("tristanIsWalkingSpeed", Mathf.Abs(inputVertical));
mySpeed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
inputHorizontal = Input.GetAxis("Horizontal");
inputVertical = Input.GetAxis("Vertical");
Vector2(inputHorizontal * mySpeed, 0f);
}
}
}
}```
you're ignoring the vertical input entirely
Yeah I was hoping to just get a movement solely on the Y axis when pressing the W and S keys
actually this script doesn't seem to do much of anything at all
in fact it has a compile error
Vector2(inputHorizontal * mySpeed, 0f); is not a valid line of code
if (isWalkingOnYVector == true)
{
if (inputHorizontal != 0)
{
float inputHorizontal = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(inputHorizontal * mySpeed, inputVertical * mySpeed);
}
}
else
{
if (inputHorizontal != 0)
{
rb.velocity = new Vector2(inputHorizontal * mySpeed, 0f);
}
}```
sorry forgot this section, i think it didnt send
my connection is shitty
let me pastebin it
again:
rb.velocity = new Vector2(inputHorizontal * mySpeed, 0f);
you are ignoring the vertical input entirely
Also all movement here:
if (inputHorizontal != 0)
{
float inputHorizontal = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(inputHorizontal * mySpeed, inputVertical * mySpeed);
}```
is inside this if statement:
`if (inputHorizontal != 0)`
so naturally it will only move if you have some horizontal input
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Here we go
That one was cut out due to shitty internet
ohhhhh fuck, how do i keep making so many basic mistakes 🤠
also you have two unrelated variables with the same name
float inputHorizontal = Input.GetAxis("Horizontal"); creates a brand new variable
why are you doing that
why are you reading the horizontal input twice
ok in all fairness
this was the first script ive programmed
and i am looking back on my mistakes regretfully
its a miracle it fucking runs

hey does ayone know if there is a simple way to not make the click event fire when the double click (double tap) event fires?
you need a state machine
yeah so I need to implement it myself?
I always have
but basically after the first click one of two things will happen
either a certain amount of time passes and you do the single click thing, or you get a nother click and do the double click thing
unfortunately you will always need the delay
Hey I'm getting an error in Visual Studio Code on my line of code shoot.performed += Fire the error is "No overload for 'Fire' matches delegate 'Action<InputAction.CallbackContext>'". Not entirely sure but I believe this is because I already attached the shoot Input to another method in another script. I attached the Shoot Input to one method for shooting in my ranged weapon and one for an attack in my melee weapon script.
it's because, as the error says, your Fire method doesn't match the delegate type
it would need to return void and accept an InputAction.CallbackContext parameter
I've never felt dumber tyvm XD
can't believe I forgot to put it in
playerControls.PlayerAction.Run.performed += i => runInput = true;
playerControls.PlayerAction.Run.canceled += i => runInput = false;
Can anyone help me? i have Run input with LeftShift, so far it works on holding shift it runs, upon releasing it stops running. what i want to know, how to achieve effect of when i press shift, it keeps running until i press it again?
Use Update
void Update() {
if (runInput) ...
}```
so i should limit performed on runinput, else canceled in update?
What?
like
if (runInput){
run performed
}
else
{
run canceled
}
No
This
Take your existing code plus my code
Oh wait sorry
I didn't understand what you meant here
You want to switch to a toggle instead of a hold?
i want to toggle run input, so it keeps running on button click
yes, that, my bad i still learn how to express problems in unity
For toggle you'd do this:
playerControls.PlayerAction.Run.performed += i => runInput = !runInput;
with that on button click it toggles run and next button click it toggles !run? so i dont need canceled input with that approach?
woah, works wonders! i would never say it's that simple 🤦♂️
another question based on that. lets say i want to put bool into options menu that gives choice to have toggled run on hold button run. so its if toggled - use this method above, else use performed-canceled inputs. i should do it in ifelse statemets, but where? can it go inside onenable() or it should go somewhere else?
you could either change the function subscriptions out or have logic inside the listener that differentiates based on the setting
gotcha, added ifelse, created ReinitializePlayerControls function and used OnValidate to have changes in realtime for changing bool value
should OnValidate() be removed when deploying a build? OnValidate works on changes from inspector, no actual ingame changes?
Are there any alternatives to LoadBindingOverridesFromJson that don't clobber processors?
Hey guys. Trying to achieve basic movement with new Input System. This is the code for my GameObject
public class MCMovement : MonoBehaviour
{
Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
rb2d=GetComponent<Rigidbody2D>();
}
public void ToMove(InputAction.CallbackContext context) {
Debug.Log("ToMove");
}
void Update()
{
}
void FixedUpdate() {
}
}```
I put ToMove in Player Input. It is attached to 2d vector binding but its not working
First image is the input action map. Second is the Player Input. I want to check if the input is coming that's all. But I cant seem to get any response in Debug console
Tried working around with it. Didnt work.
I don't see any log statements in your code - so which logs are you expecting to see?
Before I put Debug.Log() in ToMove. Nothing came. So I tried to move my object. Didnt work
you should put it back
Also show a screenshot of your console window. Are logs enabled?
You can akso use the input debugger to make sure your keyboard input is being detected in general
And finally can you show a screenshot of the action configuration? You have shown only the binding
Yes
I am pressing WASD but nothing
Edited
I'd still like to see the action configuration
The action
this is the binding
or rather the up part of the binding
Click on "Move"
and show that
Still the binding...
Ok so - can you show just eh Windows control scheme?
it's unclear which bindings are in which schemes
and your PlayerInput is set to use the Windows scheme
All are using Windows scheme
Did you save your script changes?
Is the PI actually attached to anything in the scene?
Its attached to the character I try to move
Can you show how the Windows control scheme is set up?
Also again double check the script is saved?
what to show exactly?
Hey can anyone tell me how to create a hold input? I want a value to increase with the time that its help per second. So think like charging up a meter. This is what I have for now
private void Charging(InputAction.CallbackContext context)
currentCharge += chargeRate * Time.deltatime
But this doesn't seem to work, it only increases the currentCharge everytime I press the button.
You'd have to put the code in Update
ty!
is there an easy way to reconfigure controls for a PC car racing game I made so that it can be mobile device friendly?
Define "easy"?
like not having to go into the scripts and change things manually
That all depends on how your game and your controls work and whether they're in any way touch friendly
just wondering because it's time consuming
Perhaps this will be of interest?
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/OnScreen.html
well, its a racing car, so there's gas, brake, steering, that's about it
Thanks
Does anyone know how I can add sliding mechanics to my game like the mechanics in Call of Duty and Fortnite?
does anyone know how i could setup multiple controllers??
by that i mean like controller 1 and 2 not multiple types 2 controllers at once
Use the PlayerInputManager and PlayerInput components
is there any guide for em the videos ive watched so far didnt use any of those components?
that automatically assigns them a controller?
I am making a little rpg and want to make it so if the player taps in a certain direction (eg. up, down, left, right) they will face that direction, but if they hold it, they will move in that direction
Respected, I am using unity starter assets for my first person controller,
but when i move player with joystick, the player don't move in right way. The player move slightly in a wrong way, but when I rotate it then the player move correctly ??
And the other issue I am facing the rotation speed on different devices very different, on some devives very fast, on some devices very very slow.
Please guide if someone is familiar with this type of issue.
Thank you in advance.
Can anyone help me with why this isn't working?
private void Update()
{
var direction = moveActions.action.ReadValue<Vector2>();
direction.Normalize();
scaledVelocity = direction * velocity * Time.deltaTime;
Debug.Log(scaledVelocity);
}
private void FixedUpdate()
{
rb.MovePosition((Vector2)this.transform.position + scaledVelocity);
}```
The debug shows no changes when pressing the keys, so it isn't reading the inputs.
Am I missing anything?
show the rest of the code
very possuible you're missing things yes but can't tell from this small snippet
for example did you Enable your actions wrapper object?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
You mean auto generating the input class? yes
no that's not what I mean
I mean enabling it
e.g. moveActions.action.Enable();
I'm in 2022.3 with Input System 1.6.3 and I don't have an option for 2D Vector binding...?
I figured it out.. Action Type -> Value, Control Type -> Vector2 👍
i was just routing you to the channel not to be tagged :\
Im not even sure what you're asking? wdym form inspector he refering?
yeah but you only do it once
once it generates that class you don't touch it and any changes saved in InputAction / Asset, will make it refresh automatically in that file
I cant map events in the new input systems to functions with any paramiters even InputValue
Events use CallbackContext, not InputValue which is for Send Messages
oh thanks
thats kinda confusing
I'm trying to figure out how to detect when an InputUser loses all of their paired devices. I want to create a system that kicks a local player off the game if they unplug all of their devices and don't plug something back in after 10 seconds. I'm using this code.
private void OnUserChange(InputUser user, InputUserChange change, InputDevice device)
{
if (user != this.InputUser)
return;
InputUser = user;
switch (change)
{
case InputUserChange.DeviceRegained:
Debug.Log($"Input user {user.index + 1} regained device {device.displayName}");
break;
case InputUserChange.DeviceLost:
Debug.Log($"Input user {user.index + 1} lost device {device.displayName}");
break;
default:
Debug.Log($"Something happened on user {user.index + 1}");
break;
}
if (user.lostDevices.Count == user.pairedDevices.Count)
{
Debug.Log($"User {user.index+1} lost all paired devices!");
AllDevicesLost?.Invoke();
}
}
If I plug a controller into player 2, then unplug it, I get the "AllDevicesLost" event firing. Great!
But if I plug it back in...I get the DeviceRegained event, which is great, but the AllDevicesLost event fires again
It's like it's not updating the lostDevices list immediately.
I do notice an extra "Something happened" in the log after losing a device and after regaining it
could that be the event that updates the list?
That's exactly what it was. 😛
Can't say if this is the right place for this, but does accelerometer works in editor, if the device where the editor is installed supports it?
Hey, Question - I'm trying to react to an Action, and then read the key that is associated with it to send it to an TMP_InputField that I turn on when the action happens.
This doesn't seem to work and I think it's not a good practice; how do I actually read Keys as Chars or Scancodes with InputActions?
InvalidOperationException: Cannot read value of type 'int' from control '/Keyboard/anyKey' bound to action 'UI/AlphaNumeric[/Keyboard/anyKey]' (control is a 'AnyKeyControl' with value type 'float')
I tried the Value types.
(the feature I want to build is a filter input field that becomes visible then the user starts typing while a UGUI window is focused, kind of standard stuff)
Why does it say it's "Float"?
InputSystem.onEvent
.ForDevice<Gamepad>()
.Where(e => e.HasButtonPress())
.CallOnce(ctrl => Debug.Log($"Button {ctrl} pressed"));
Trying something like this now.
This gives me really weird IDs - seems like the IDs are rotating?
(all the same key :D)
According to docs, this is tricky 😄
I will implement ITextInputReceiver instead.
Hmm I did not understand that one right 😦
Keyboard.current.onTextInput´ I figure.
Hi, we are experiencing the same issue with Input System 1.6.3, Select and Start buttons are still swapped on Steam Deck
Anyone can direct me to information on how I can listen for player input on another object?
Basically I want to do this:
Have a sign object with a script, when the player press the "Attack button" in front of the sign, it activates the dialog box object in my hierarchy.
What I think I need to do is put the input.xx.xx.xx.performed += Attack_performed on the sign and when the player attacks, the dialog box activates, etc
So far, from my testings, if I do that, the event gets fired twice at the same time and nothing works out.
Anyone can help me?
put an Interactable component on the sign
have a script on the player that looks for such components on nearby objects
and calls a function on that component when you press the button
I have a collider on the sign already
ok that's a good first step
oh, so in the player script, I guess I could check for the tag of the collider and if its a sign, I do the whole dialog system
Here's an example I wrote for someone yesterday:
#💻┃code-beginner message
Hello! I need a hand with the "new" input system. I'm currently working with both so i can slowly integrate the new input system but for some reason i cant get it to detect any input values
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Movement : MonoBehaviour
{
Vector2 movement;
public float Speed, angle;
public Rigidbody2D rb;
public Camera cam;
public bool HasGun;
public Animator animator;
void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
private void OnMovement(InputValue value)
{
movement = value.Get<Vector2>();
Debug.Log(movement);
}
void FixedUpdate()
{
FollowCursor();
animator.SetBool("HasGun", HasGun);
//movement.x = Input.GetAxisRaw("Horizontal");
//movement.y = Input.GetAxisRaw("Vertical");
if(!HasGun)
{
animator.SetFloat("MoveX", movement.x);
animator.SetFloat("MoveY", movement.y);
animator.SetFloat("Speed", movement.sqrMagnitude);
}
else
{
animator.SetFloat("Speed", movement.sqrMagnitude);
}
rb.MovePosition(rb.position + movement * Speed * Time.fixedDeltaTime);;
}
void FollowCursor()
{
Vector3 point = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1));
point = point - transform.position;
angle = Mathf.Atan2(point.y, point.x) * Mathf.Rad2Deg;
animator.SetFloat("Angle", angle);
}
}```
I assume you're using a PlayerInput component?
Can you show the inspector for the object that has the Player into and this script on it?
How can I create a settings menu for my fps game? I want to know how I can build a scene where the player can change their settings. I am confused how I can do that while using the new input system?
To use the new input system with UGUI you need to use the Input System UI Input Module:
My debug interface turns off my "Look" action. When I read it after re-enabling the action, my camera spins around, because a very large mouse movement occurred since the last read.
Is there a way I can clear that?
I can't just call ReadValue on every action in its action map, since that requires knowing the correct type to read
maybe Reset? let's find out
hm, nope
oh, I think I get it: the debug menu unlocks the cursor
the cursor then snaps back to the center when the cursor is locked
that appears to cause the next mouse delta read to give a big value
if I move the mouse right and then close the debug menu, my next mouse movement makes the camera spin left
well, that's a bit annoying
I ran into the same issue in an older project where I was using the Player Input component
so I got a callback whenever the mouse moved
To solve the issue there, I just ignored the first event after the mouse was re-locked
here, however, I'm using ReadValue to read the value every frame
so I see a bunch of [0,0] results until i re-lock the cursor and then move the mouse
I guess I'll just ignore the first result that isn't [0,0] after re-locking the cursor
Quick question regarding the new input system.
I was wondering if it was possible to create an action that can be triggered by multiple key combinations.
For example: action "thing" can be triggered by key combinations 1."A+B+C" or 2."X+Y+Z".
I have managed to make this work using the old input system but can't find much documentation on how to do this using the new system, i'm thinking that I've missed something in the docs.
From what I've found, you can bind an action with 2 keys required using composite binds, but not N binds.
Any ideas?
Quick example of what i mean.
this is sick how did you manage to do this? I am also trying to create something like this
lol thanks 🙂
It's using the legacy input system.
why is Right Stick [Gamepad] disabled ?
I've created a WASD movement, then another action
but unable to select Right Stick
Sorted
Interestingly, it seems that it is indeed possible that the new system supports a multiple key bind to an action.
It seems to support 2 button binds. e.g "X+Y" and even three button binds like "X+Y+Z.
Sadly, it does not seem to support 4+ button binds. e.g "A+B+C+D"
Some example code if anybody wants to experiment in the future
public class Test : MonoBehaviour
{
private InputAction Action;
void Start()
{
Action = new InputAction("MultiButtonAction", binding: "*/<Button>/press");
Action.AddCompositeBinding("ButtonWithTwoModifiers")
.With("Button", "<Keyboard>/a")
.With("Modifier1", "<Keyboard>/b")
.With("Modifier2", "<Keyboard>/c");
Action.AddCompositeBinding("ButtonWithTwoModifiers")
.With("Button", "<Keyboard>/x")
.With("Modifier1", "<Keyboard>/y")
.With("Modifier2", "<Keyboard>/z");
//.With("Modifier3", "<Keyboard>/A"); <- will cause error
Action.Enable();
}
// Update is called once per frame
void Update()
{
if (Action.triggered)
{
Debug.Log("testr");
}
}
}
Cool keep up the good work.
so uhhh... the input system is sending error messages after I tried to add a jump input
this is but a few bricks in the wall of error messages cascading down my screen as a result
any suggestions?
also sorry if it's at all annoying that I just popped into the server to ask stuff
You have duplicate scripts
Look at the file paths in those errors
Also you shouldn't name your class PlayerInput since that exists already and you shouldn't put a space in the filename
i have a first person camera system setup with the new input system and its jittery and i cant figure out why controls.player.mouselook is a vector 2 set to mouse delta
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
[Range(0f, 100f)]
[SerializeField] float mouseSensitivity;
public InputMaster controls;
[SerializeField] Transform playerBody;
float xRotation = 0f;
[Header("Clamp")]
[SerializeField] float minClamp;
[SerializeField] float maxClamp;
private void Awake()
{
controls = new InputMaster();
Cursor.lockState = CursorLockMode.Locked;
}
void OnEnable()
{
controls.Enable();
}
void OnDisable()
{
controls.Disable();
}
void Update()
{
float mouseX = mouseSensitivity / 100 * controls.Player.MouseLook.ReadValue<Vector2>().x;
float mouseY = mouseSensitivity / 100 * controls.Player.MouseLook.ReadValue<Vector2>().y;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, minClamp, maxClamp);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
} ```
I had somewhat same issue
my problem got fixed after moving the look function to lateUpdate instead of update
and 2nd thing I did was to change update mode
go to project settings
then select Input System Package
then change Update Mode to Process events in dynamic update
I think now its set to that by default but you can try nonetheless
weird i had a very similar issue to this not so long ago. And i can't for the life of me remember what i changed to fix it.
I think it was either somthing to do with the transform i was rotating being a child of an entity. Or it was something to do with not including
Time.deltaTime()```
Really can't recall what it was though.
I am trying to debug why my touch inputs are not being handled correctly.
This method is only called BY touching the screen, but activeTouches returns zero, which is impossible. How can there be no active touches but also call the method that only activates when there ARE touches?
private void OnTouchStarted(InputAction.CallbackContext context)
{
if (Touch.activeTouches.Count > 0)
{
Touch touch = Touch.activeTouches[0];
Vector2 startPosition = touch.startScreenPosition;
Debug.Log($"Touch started at: {startPosition}");
}
else
{
Debug.Log("No active touch being performed, yet OnTouchStarted was called. Impossible state detected.");
}
}```
is the action map incorrect?
enhanced touch support is on so it should be working but touching it returns no touch is being performed, its insane, it makes no sense
how can it return no touch as a result of me touching it? its not physically possible
getting distressed that I cannot find the cause of this bug
The enhanced touch API isn't meant to be used in conjunction with Input Actions
As per the example here it's meant to be read in Update I believe:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/api/UnityEngine.InputSystem.EnhancedTouch.EnhancedTouchSupport.html
oh, running on update doesnt seem like good design if its going to be on mobile
Or am I stupid and wrong and should do it this way?
I only used enhanced actions because I googled it and thats what google results told me to use
there's nothing wrong with Update on mobile
the input system polls input each frame under the hood anyway
Just don't go crazy and have hundreds of objects polling input separately
Gotcha, will do
unfortunaly none of those worked
Hi everyone! I find myself blocked on creating a simple input action that associates the mouse click and primary touch to some code. What I want to get is the screen position of the event. I am able to find in the 'performed' context of the action but on the 'canceled' context, the value does not show. Please see below my code, action and context logs. Please help me understand how I can get the release screen position of the action event as I can get it on the initial performed state. Thank you!
make a separate action for pointer position vs pointer click
attaching action screen as the first one was not showing it properly
so in OnSelect you can do:
Vector2 pointerPosition = pointerPositionAction.ReadValue<Vector2>();```
or even try this without a separate action:
```cs
Vector2 pointerPosition = Pointer.current.position.ReadValue();```
hm... this might be the way... I read in the docs that both Mouse and Touch inherit from Pointer...
thank you @austere grotto ... testing now 🙂
working now, thanks again!
Even though I modified my script to pool the Pointer directly, it is still weird that the release context won't get the position... maybe it's some sort of bug...?
the verticalrotation does not work, and for some reason horizontal rotation is much faster than before
i can delete thos right?
They are for the URP rendering debug menu I believe
ah
i will keep them then
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
is the Classic Input system for Unity better or the SystemInput Package better
The new input system is significantly better
so the package thingie
im just following a tutorial and i didn't know this "new input" thing existed until now lol
i'm very new to unity but if its significantly better than im excited to try it out
Yeah it is confusing at first but clearly a way better system once you understand it. This helped me a lot. https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/Workflows.html
I downloaded the 1st person proyect and added the 3 prefabs necessary to work, input system added and all good, but the ui doesn't work, the mouse also hides
I have this in my canvas object
And this is the player, I hate this input system but I have to use it to get a nice FP POV
What UI do you have that isn't working
How is it set up
I added all the input setting that worked in other asset in the time I was not here, now it works, only when the player is deactivated
Notice how is another action asset now
but the mouse gets captured and disapears, that's the problem
Wow, I finaly solved it, turns out there are other scripts that can't be disabled btw, which hide the cursor indeed
The default actions should've been fine
Yeah, I could have added all the movement settings there, instead of all the click, cancel, submit, and a bunch of others, but I leraned a bit more of the input system introducing so many things
I was using this
Is it good idea to disable the player input component so the camera stops moving when I hit escape and show the ui?
You can leave the default actions for the UI input module and use your custom one for gameplay
That's one way or you can disable the action map for gameplay
how do I detect if the player is looking at a gameobject and has clicked on it?
IPointerClickHandler or the EventTrigger component
Your question is extremely vague. What are you asking?
I have an image on which I put the On-Screen Stick component and binded to it the left gamepad stick and it works as intended and then I have a button with the On-Screen button component and I binded the W on the keyboard and it also works as intended, howewer if I want to have my finger on both at the same time it breaks and registers only the first one I held, is there any way to fix this?
See the tutorials pinned to this channel
to add more info - when the button is held down first, I can move the joystick around but it just doesn't register it
when I play on pc holding down the equivalents of this (left stick and W/S) works but not on mobile
just tested it again and it doesn't allow me to move the joystick around when I press the button first
oh and sometimes the stick doesn't work at all
anyone else having problems with the input system on UI navigation? some times when i press on my DS4 d-pad it doesn't register or register it duplicated, not a controller or script issue
a little demonstration of the issue, all i'm doing is pressing the dpad button down
you can see it jumps a button some times
it is detecting my dualshock4 controller as both DualShock4 and XInputController, probably something related to that, i have different situations when i disable one or another:
DualShock4GamepadHID enabled + XInputControllerWindows enabled = some times it doubles the pressed dpad input, making it jump a button
DualShock4GamepadHID enabled + XInputControllerWindows disabled = some times it doesnt detect if i press on the dpad
DualShock4GamepadHID disabled + XInputControllerWindows enabled = works flawlessly
I'm trying to get into TDD, just messing around and trying to make a simple test to pass, here it is:
public class PlayModeTests : InputTestFixture
{
public override void Setup()
{
base.Setup();
SceneManager.LoadScene("Assets/Scenes/Main.unity");
}
[UnityTest]
public IEnumerator Clicking_Card_Selects_It()
{
var handPanel = GameObject.Find("HandPanel");
var card = handPanel.transform.GetChild(0);
var mouse = InputSystem.AddDevice<Mouse>();
Camera camera = GameObject.Find("Main Camera").GetComponent<Camera>();
Vector3 screenPos = camera.WorldToScreenPoint(card.transform.position);
Set(mouse.position, screenPos);
Click(mouse.leftButton);
yield return new WaitForSeconds(0.1f);
Assert.That(EventSystem.current.currentSelectedGameObject, Is.EqualTo(card.gameObject));
}
}
And the test doesn't pass: the expected value is Card, but was null.
And in the console it gives me this monstrosity:
Parameter name: value
UnityEngine.InputSystem.Users.InputUser.set_listenForUnpairedDeviceActivity (System.Int32 value) (at Library/PackageCache/com.unity.inputsystem@1.5.1/InputSystem/Plugins/Users/InputUser.cs:412)
UnityEngine.InputSystem.PlayerInput.StopListeningForUnpairedDeviceActivity () (at Library/PackageCache/com.unity.inputsystem@1.5.1/InputSystem/Plugins/PlayerInput/PlayerInput.cs:1685)
UnityEngine.InputSystem.PlayerInput.OnDisable () (at Library/PackageCache/com.unity.inputsystem@1.5.1/InputSystem/Plugins/PlayerInput/PlayerInput.cs:1720)```
What am I missing?
I have following setup in my hierarachy
Hello guys,
This morning I've got this error :
Library/PackageCache/com.unity.inputsystem@1.6.3/InputSystem/Plugins/XR/XRSupport.cs(452,49): error CS0234: The type or namespace name 'GoogleVr' does not exist in the namespace 'Unity.XR' (are you missing an assembly reference?)
Library/PackageCache/com.unity.inputsystem@1.6.3/InputSystem/Plugins/XR/XRSupport.cs(456,49): error CS0234: The type or namespace name 'GoogleVr' does not exist in the namespace 'Unity.XR' (are you missing an assembly reference?)
I delete the Library folder but doesn't solve the issue
I don't even use android or VR in my project
And package manager doesn"t provide me the 1.7 update for input system ?
question - for the UI "OnClick" function, is there a way to trigger this through the keyboard? Using the EventSystem, I can move around using WASD and the arrows, but I can't select anything
The "Submit" button in the UI input module will trigger a button click for the selected button
default is "Enter" I believe
does new Unity input system have binding which maps to ctrl on Windows and cmd on Mac?
Hi I have got problem with my script. So Im using old input system and script is for dragging objects. Everything works well, but only with Left Button [Mouse]. When I'm trying on the phone nothing even works
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Trying to set up polling, but doesn't seem to work
polling would be this:
void Update() {
Vector2 lookInput = _inputActions.PlayerMap.Look.ReadValue<Vector2>();
}```
I'm confused because my friend who currently is unable to reply is using this
public PlayerInputProcessor(Character owner) : base(owner)
{
InputActions = new DefaultInputActions();
InputActions.Enable();
}```
and this
```cs
if (InputActions.Gameplay.Move.ReadValue<float>() != 0)
{
_moveGoal = GetPointerPlanePosition();
}
would this be a correct way to set up? Doesn't seem to work
Respected, I am using starter assets for my first person controller, but when I inactive the player and then active it, then player starter input assets updates the values of move by itself.
Can someone please enlighten on this point.
And how can I save it?
Thanks
what is PlayerInputProcessor and what does it have to do with the other code you posted?
I solved it. It was a wrong variable apparently in one of parts.
I'm making a controls rebinding menu to my game. Online I read that you can do InputAction.PerformInteractiveRebinding().
This is my code:
CurrentMap.FindAction("Jump").PerformInteractiveRebinding()
It complains that the function doesn't exist at all... What am I doing wrong?
Hey, does anyone know how to manually invoke an InputAction? If the InputAction is disabled, I'd like it to not invoke exactly as if the player had performed the action.
Using Unity's Input System, how do I avoid using two actions (left click, shift + left click) when using a modifier composite? I've read that their used to be a workaround needed but has it been fixed since? Can't find much information and a little confused.
PerformInteractiveRebinding() returns a monad called RebindingOperation which needs to be set up with a lot more stuff, including an OnComplete action.
Yeah, that has been solved now... see here:
@stone ether Once your RebindingOperation object is setup, you call .Start() on it to begin. You also must dispose of it in the OnComplete method later.
Finally, think this has fixed my problem. Thank you.
not updating the api breaks it and updating the api breaks it
Hi everyone
I am using the new input system. I have set up gamepad stick for touch input. The input actions are configured for both keyboard and gamepad. I am facing this issue where the UI controls stop accepting or processing input.
In the above video, I use the left stick to provide forward thrust but it stops working randomly.
I could find forum posts about this but none of the solutions worked for me. has anybody else faced the same issue and was able to resolve it.
not sure if this is better in here or #🧰┃ui-toolkit but my elements' focus ring is skipping over some inputs depending on the direction you are navigating, if you nav down with dpad-down or down-arrow it skips invert y and if you navigate upwards it skips view sens
according to the docs the focus order should be DFS which is the same as their layout order.
i tried setting the exit tab index to 2 to ensure it is last but the problem persists
seems to have come good. the settings element had a dodgy align-items that might have been confusing the focus-ring algo
I know. I managed to fix it by restarting my computer... Also did you even read the question
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/UISupport.html#virtual-mouse-cursor-control can someone explain why i cant turn this on and off..
like i get its different tracking for touch devices
How I can attach my joystick to my input system
that would be the same as attaching anything else to your inputsystem
you should just add a binding for it
Hey, hopefully a quick question:
Wondering if there is built-in functionality to disable a specific sub-input on my input actions?
In my case, my professor is requiring we have either controller, WASD, or TFGH (alt to WASD) controls active at one time not all three. It seems like the "move" input action could house all these inputs but then they'd all be active at the same time. I tried doing a simple move.Disable(); in the script but that disables the entire input action rather than a specific part of it.
Note: I'm using the Player Input component rather than the generate C# class due to my need to perform interactive rebinds (which from what I've read can't be done with the generate c# class)
Theoretically, I could just make another input action for each type (controller, wasd, etc.) but that seems like a somewhat weird solution to a problem that's probably quite simple.
I did check the manual but didn't see any reference to this specific issue
Interactive rebind can be done with the generated wrapper no problem
Google multiplayer on one keyboard in new input system it just requires a little scripting for device recognition and I believe a control scheme
Any resources on this because everything I've read or watched indicates otherwise 😅
What's stopping you from doing it and who said it can't be done? There's nothing special about the wrapper. It's a regular InputActionsAsset underneath
Yep
Hmm, these all seem like over the top solutions. Is there not a way to just disable WASD, controller, etc. inputs individually? That seems like it be the simplest way to go about this.
Make them different input actions
Hey guys, I have an Input Action Asset that I am assigning to a Player Input component on an object (let's call it Player). I have a separate object called Cursor, which also has a Player Input component, and I am attaching the same Input Action Asset to it. However, when I do this, it causes the inputs on the Player to not work (using Keyboard and Mouse) -- the inputs only work with my plugged in controller (unplugging the controller fixes the issue). Is there any solution to this?
i need to have a bool that changes based on whether or not the player is using a gamepad.
i know i can call an event every time a controller changes from keyboard to a gamepad, but how do i check what controller is currently plugged
Is there any way to use a global action map or something or to have multiple action assets active in one scene?
You really only want one of those playerinput conponents per player/set of keys on a physical device (like WASD). But there is a "consume input" option somewhere. I wonder if disabling that would help
You can do both, not a problem
they're just objects and you can reuse/pass around references as you wish, or have a single manager script that handles it centrally
Alright then, thanks!
I have a PlayerInputActions set up and a PlayerInputController script set up. I set up the Inspector as I thought was right. Went to play the game, and no actions are happening.
If I press a button or stick left, it does show the value.
So that part is fine.
Can I paste my C# code? I sorta got it from a tutorial.
yes, just format it properly: !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerInputController : MonoBehaviour
{
[SerializeField] float _jumpSpeed = 500.0f;
[SerializeField] float _jumpForce = 300.0f;
Vector3 _movement;
Rigidbody _rb;
void Awake() => _rb = GetComponent<Rigidbody>();
void FixedUpdate() => _rb.AddForce(_movement * _jumpSpeed * Time.deltaTime);
public void OnMove(InputValue value) => _movement = value.Get<Vector3>();
public void OnJump(InputValue value) => _rb.AddForce(Vector3.up * _jumpForce);
}
I tried to learn from the docs but couldnt figure out how to do the script section so watched someones video on theirs which was only a few months ago. XD
I was trying my best 😭
I feel like a dumbass.
you should never be multiplying deltaTime into AddForce
https://prf.hn/l/dlXmbpN - Asset Store Black Friday Sale!
Use Code - JASONWEIMANNBF22 for additional 10% off (cart must be over $100 for it to apply)
https://www.kenney.nl/ - Check out the KennyNL Assets
https://game.courses/beginner/ - Free GameDev Course for Beginners
https://bit.ly/3sKGagG - Game Architecture Course - Advanced Course
http:/...
It worked for him ,weird. 😐
well it will "work"
it's just pointless
and it's the reason his force numbers have to be so large
500 / 300 are huge numbers
Whats the proper way these days?
Th proper way all days is not to use deltaTime inside your AddForce call
what numbers did you set in the inspector
Invoke needs different parameters
CallbackContext
What method are you expecting to see
see the code here
it's different from yours
But i don't understand why you're switching to Unity Events
Then what do people use?
Okay well now I feel like this is JavaScript Framework terrority.
What one is more popular?
I do not want to leanr4045943904239523495249592390 things
I'm almost 50, this is a teens/20s/30s thing.
What are you trying to do
I'm not as sharp now. :/
why are you jumping around different things
I'm trying to Jump
So what's wrong with the first way
tehre is no common way
Even a dev said he uses this.
then this way
everyone who is making games is a dev
getting closer
I tried their example
Still no response.
It might be my shitty Switch Pro Controller, it seems to suck when it comes to Bluetooth.
Case in point xD
Yeah if your joystick is not connected it's not going to work of course
looks like you have some exception in your code though
I fixed that
Plugged in a usb cable, much better too. Now stable.
I def need a xbox controller again.
All fixed.
I am trying to make a local multiplayer character select menu similar to like a fighting game where each player can navigate the menu separately but on the same UI. Unity has the Input System UI Input Module that lets navigating the UI easy, you don't need to figure out yourself what button to select yourself as unity will do it for you. The problem is this only seems to support 1 player at a time as this module doesn't have a way to track each player input separately on the UI. Anyone have suggestions on how I can make this happen? I can manually track by not using the module but figuring out what button to navigate to based on current selected button seems like a lot of work. I could be overthinking this or missing something so I figured I'd ask here, maybe someone here has done this before.
Can I get some attention from InputSystem team for my question please? Thank you.
https://forum.unity.com/threads/how-to-initialize-input-system.1489489/
This is a community server
If you want official Unity support contact their official support channels
Yea. Actually it doesn't need to be for official Unity people. Maybe someone from the community can help me.
Why is multiplayer so problematic with new input system ~.~
Talking about online or local multiplayer? What challenges are you facing?
I had an issue where in a new ParrelSync instance it was listening from both instances, fixed it though thanks for reaching out.
What was the fix? Might be relevant for me soon 😅
tbh it wasn't about the new input system but I wasn't doing the right checks in netcode
Ah, I see 👍
Guys i need another look on these scripts, New input system is killing me .started event just fires twice if i time perfectly left button it fires and then it fires again if i release the left click
public abstract class Weapons : MonoBehaviour
{
protected Characters.PlayerCharacter _player;
public PlayerCharacter Player { get => _player; set => _player = value; }
protected void Awake()
{
_player = Characters.PlayerCharacter.Instance;
}
protected void OnEnable()
{
if (_player != null)
RegisterForShoot();
}
protected void OnDisable()
{
UnregisterForShoot();
}
public virtual void Shoot(InputAction.CallbackContext context){}
protected virtual void RegisterForShoot()
{
if (_player.InputAct != null)
{
_player.InputAct.Player.Fire.started += Shoot;
_player.InputAct.Player.Fire.Enable();
}
}
public virtual void UnregisterForShoot()
{
if (_player.InputAct != null)
{
_player.InputAct.Player.Fire.started -= Shoot;
_player.InputAct.Player.Fire.Disable();
}
}
}
{
public override void Shoot(InputAction.CallbackContext context)
{
if (context.started == true)
{
Debug.Log("Pew");
Bullet bullet = _player.BulletPool.GetChild(0).GetComponent<Bullet>();
Vector3 _endPosAim = new Vector3(_player.AimObject.transform.position.x, _player.AimObject.transform.position.y + 1.5f, _player.AimObject.transform.position.z);
//RaycastHit _hitInfo;
//if (Physics.Linecast(_player.AimStart.transform.position, _endPosAim, out _hitInfo))
//{
// _endPosAim = new Vector3(_hitInfo.point.x, _player.AimObject.transform.position.y + 1.5f, _hitInfo.point.z);
//}
// Set the maximum distance and destination of the bullet
bullet._start = _player.AimStart.transform.position;
bullet._destination = _endPosAim;
// Activate the bullet game object
bullet.gameObject.SetActive(true);
if (_player.VirtualCamera.GetCinemachineComponent<Cinemachine.CinemachineBasicMultiChannelPerlin>().m_AmplitudeGain < 0.3f)
StartCoroutine(CameraShake());
}
}
IEnumerator CameraShake()
{
_player.VirtualCamera.GetCinemachineComponent<Cinemachine.CinemachineBasicMultiChannelPerlin>().m_AmplitudeGain = 0.3f;
yield return new WaitForSecondsRealtime(0.1f);
_player.VirtualCamera.GetCinemachineComponent<Cinemachine.CinemachineBasicMultiChannelPerlin>().m_AmplitudeGain = 0f;
}
}```
hm i already asked it here once, but does somebody know how to bump the sampling rate for HID devices ? they are sampled with 60hz, but i'd really love to bump it up a notch. Got a few "joysticks" but 60hz is just not fast enough for my needs.
can somebody help me with the input system
when i "subscribe" a input to a certain function it just doesnt get called when i press the right input
How do you subscribe? What does the InputAction asset look like?
Hi im using the new input system for the first time. Im using the behavior "Invoke Unity Events". im trying to access an input that is stored in a script but the script is on different objects/prefabs. How do i get a reference to this??
I'm trying to make my UI navigable with a gamepad and I've come across a weird issue. Whenever I try to "click" a button the submit event seems to happen twice. I checked and it's not my controller's fault (I check both wired and wireless), nor is it because I have another input with the same binding (I put submit on Select since it's not used by anything) and other than some small changes to test things out I have not modified anything in the Input System. Any idea what may be the cause of this issue, I've been trying to fix this for the past few hours?
Update: I also tried making a new submit action and setting in the event system, but with no success...
Whenever I'm changing between mouse and virtual mouse (pairing/unpairing virtual mouse), i sometimes get an error:
Could not find active control after binding resolution
UnityEngine.InputSystem.Users.InputUser:PerformPairingWithDevice (UnityEngine.InputSystem.InputDevice,UnityEngine.InputSystem.Users.InputUser,UnityEngine.InputSystem.Users.InputUserPairingOptions)
this error is very frustrating because it does not tell me wtf I have to do to make it not happen -.-
This is more a general coding issue it sounds like. Try looking through this site https://unity.huh.how/programming/references
its part of the new input system tho no?
You're trying to access variables from another script, right?
it has to do with the "Player input" component
no basicly in the player input component im trying to get the reference to the script
ill send a picture quick
its with the "PickUp" one
i need something as an object to use as a reference
but the script where its in is used multiple times in prefabs
how do i get the reference to the input then?
or is this just not possible XD
i think i figured out a workaround for it
but if there is a way just let me know XD
Well... you can subscribe through code...
But honestly, that feels like the inverse of what you want. The PLAYER should be calling pickup and maybe passing values IN to the object, or calling a method on it..
But either way, you can subscribe in code. Can't remember how right now sorry.
OR, you can create a public InputAction pickup variable on the thing you want and do the controls on that.
Ok perfect, cause I wasn't sure
yea i found something out just now but ill look into what u sent and see if it works better
thank you!
ok nvm my way doesnt work
anyone tried to do "fighting game inputs" with new input system, like hadouken, shoryuken inputs? I can´t really find how to start
Works the same as in any input system. You need to model it as a state machine
Has it any example or any docs about that?
The input system? No
The input system isn't related to the fighting move state machine
It's just for detecting the actual button presses
Ok, thanks
I'm sure this was mentioned endless times already: How can I make user-rebindable keys?
So instead of checking isKeyPressed('a') I'd go for isKeyPressed(Keys.leftDirection) or so
Use a KeyCode variable or better yet switch to the new input system and use the rebinding support it has which is much more robust
Thank you!
Using CustomInput, will I be able to make an NPC controller that determines its own inputs, and provide it to any of my entities that read CustomInput?
No idea what CustomInput is
Oh I found it while looking for unity's new input system... Hmmm
sounds like a custom thing someone wrote
can somebody help me with my game. It was just working the other day and now when i try to take input with the new unity system it just doesnt work. ill send screen shots right now
hello, my input system doesn't work. I already make InputAction, assign it to PlayerInput, set event callback, but when I pressed ESC it's not being triggered, why? Where did I do wrong?
hi, i have a problem with input system. Thing is, i wrote a simple code that makes 2d characher jump and roll. Thing is somehy unity rarely detects input. Seems like most of input doesnt get read and unity just skips most part of it. I tried to adjust fixedupdate interval up to 0.0095 but that helped only slightly if helped at all. Did anyone had this problem?
For jumps i use addForce with ForceMode.Impulse. When unity does read the input everything seems to work fine
private void FixedUpdate()
{
//fix jumps. He cant jump in a sequence, right on landing
if (Input.GetMouseButtonDown(0) && IsOnGround == true)
{
this.rigBod2d.AddForce(new Vector2(0, yJump),ForceMode2D.Impulse);
Debug.Log("Input wa read");
//IsOnGround = false;
}
}
Does it work when you start the game with no controller connected my game has the same problem using keyboard and controller in the same action
This is coming from #1064581837055348857 , how could I save and then get actions from an InputUser? I have an automatically generated C# class, or maybe the original asset, and I need to read stuff from there for saving in an Input bank
Right now thinking of doing something like ```cs
//This should create a new user.
InputUser newUser = InputUser.PerformPairingWithDevice(pairWithDevice);
//Associate the Game Input Actions
GameInputActions a = new();
newUser.AssociateActionsWithUser(a);
But I honestly have no idea?
pairWithDevice is a InputDevice btw
Which I get from an InputAction.CallbackContext context
Like, the objective is just getting the values from the actions and stuff
Hi there, I hope someone can offer me a tip. This is the first game that I am using the new input system in, and I am having trouble with two actions. I have the S key assigned to going prone. I have another action assigned with One Modifier (S and Space, Space being the modifier), to jump down. I don't know how to determine that the S and Space is being called, and not the S. The functions for both actions are being called.
Is it possible to do this? Or is there some code that I have to add to my code to be able to tell the difference. Or is this something that it is just better suggested to have a different key for prone and jumping down?
Thanks.
i wanna make a "press [X] to do action" thing, how do i get the binding via script?
Have you checked the docs yet?
there are so many idk which one to check
You look at the thing you're actually interested in
Ignore the rest
You want to know the binding for an input action
So check the docs for that class
i used this to get the line
inputScript.playerInputActions.NormalPlayerMovement.Vault.interactions.ToString()
and it just gives an empty string
because inputactions does not contain a definition for binding
Not doesn't but maybe search the page for "binding" and see what comes up
212 results
i searched and found nothing i can understand
Is there a reason to use multiple assets over multiple action maps? Any pros and cons? Asking cause because searching for an answer from previous posts could be difficult with the way it's worded.
I GOT IT AFTER AN HOUR
string bindingName = InputControlPath.ToHumanReadableString(inputScript.playerInputActions.NormalPlayerMovement.Vault.bindings[0].effectivePath, InputControlPath.HumanReadableStringOptions.OmitDevice);
if anyone wants to do a "press [x] to action", you can use this code. i knew it took a lot of time and you got desparate enough to search this in the message search
those things aren't mutually exclusive
Well, yes, but I haven't personally found any good examples and I'm still a beginner with the Input System.
It's hard to give pros and cons for things that aren't mutually exclusive
u need to learn unity Actions
its a little bit different than events, but perform similarly
i assume u have an action map, and the action needed
u should have an input manager, to get the map needed
and then on the script that relates to any input, u need to register the input action u need
is there a way to tell if the player has switched inputs from mouse to gamepad?
Why does the new input system run my script in invoke unity events multiple times at one button press?
I just use F11 as keyboard binding and even if I select only on "button realese", my script does run 3 times before it think its over.
Did I missed something or it this a Unity Bug?
Theres are 3 different phases of the button press
started, performed, canceled
You can check which one it is in your code
Just a bug in your understanding 😉
But not in Unity Invoke?
I connected my script in the player input, that triggers a fuction of thw script.
I also tried to add "on realese" inside of the action keybind map and its still not working like it should.
It's working like it should
It's not working like you expect
There's a difference.
Not sure what you mean by "but not in unity invoke?"
I need help getting my controller working with the old input system.
I have "Horizontal" and "Vertical" hooked up to the X-axis Joystick and Y-axis Joystick respectively
When I move the joystick left-right it affects "Vertical"
I have no way to change "Horizontal"
One problem might be related to the fact that the blue ring around the home button on my pro controller is not on unless I'm in "Test Device Inputs" in Steam settings, should it be on?
Hopefully someone can help me with this, it's breaking my brain
make sure your axes are set up properly in the input manager. However I have heard lots of complaints that the switch pro controller really doesn't play well with Unity
Ok I'll go grab an xbox controller and test it. Are the problems mainly in the editor and once I make a build it'll work fine or do I need to fix these problems before I make a build?
I don't know, I've never worked with a switch pro controller
Switch pro works just fine with the new input system if you are willing to switch to it.
I Invoke C# Event, You need to call the Input Action and the Button inside of it. But in Unity Invoke Events. You call the script.
In my case, I call the:
public void F11FullscreenToggle()
{
...
}
The only issue is, that this F11FullscreenToggle does 3 times being executes while I only pressed "F11" once, inside of my InputActionControls.
Yes I explained the reason and how to fix it
First off you need to add the callback context parameter to your function
Then reassign it from the dynamic list in the PlayerInput thing
Then you can check the phase of the event in the code
Press Only is the option.
BEcause I do not use Invoke CSharp Events, so calling just the fuction should be enough.
I know that this is true based on Unity CSharp Events, but I dont use them.
[codeblock]
public class F11_FullscreenToggle : MonoBehaviour
{
private int FULLSCREEN_Speicher_Value_int;
[SerializeField] private TMP_Dropdown Dropdown_Fullscreen;
public void F11FullscreenToggle()
{
SaveGame.Encode = false;
FULLSCREEN_Speicher_Value_int = SaveGame.Load<int>("optionmenu_FULLSCREEN_Value_File.txt");
bool WurdeErstereIfBereitsAusgefuehrt = false;
if (FULLSCREEN_Speicher_Value_int == 0)
{
print("Fullscreen ON");
Screen.fullScreen = true;
FULLSCREEN_Speicher_Value_int = 1;
SaveGame.Save<int>("optionmenu_FULLSCREEN_Value_File.txt", FULLSCREEN_Speicher_Value_int);
Dropdown_Fullscreen.value = 0;
FULLSCREEN_Speicher_Value_int = 0;
WurdeErstereIfBereitsAusgefuehrt = true;
return;
}
if (FULLSCREEN_Speicher_Value_int == 1 && WurdeErstereIfBereitsAusgefuehrt == false)
{
print("Fullscreen OFF");
Screen.fullScreen = false;
FULLSCREEN_Speicher_Value_int = 0;
SaveGame.Save<int>("optionmenu_FULLSCREEN_Value_File.txt", FULLSCREEN_Speicher_Value_int);
Dropdown_Fullscreen.value = 1;
return;
}
}
}
}```
It's true for Unity Events
See how the event has CallbackContext as a parameter? You need to do that
Why does some Panels in the Inspector have (CallBackContext) and some (PlayerInput) ?
Wait what, why?
I thought Invoke is only UI and Inspector based and the CSharp does only need those specified button code?
What is CSharp for then?
This makes it truely more complicated than I expected it.
That doesent seem be right just to get a simple F11 Kebind into it.
You have to get the input, put them in a awake, onenable, ondisable and then the actual InputAction.CallbackContext.
thats why I changed from Invoke Csharp to Invoke Unity, to avoid all of this.
its a lot of work to setup just for a simple Keyboard keybind and makes the code less-readable.
Is there a option or field in the InputActionControl or the Inspector to get directly the only one simple input of a Keyboard keybind?
What even is the difference of "Invoke CSharp Events" and "Invoke Unity Events"?
- I thought its because CSharp need to access the keybind from the code while Unity Events have everything in the Inspector as button behavior.
Even ChatGPT told me that Invoke Unity Events are there to allow you to assign Unity Events directly in the Inspector while CSharp needs no make everything in code.
Yes unity events are to assign in the inspector
Invoke C# events is very different
Its a lot with Awake, OnEnable and OnDisable just to initialize the Input System.
you only need that if you're manually subscribing to events on the action asset
would you prefer Invoke Unity or Invoke C Sharp?
Cause I thought it would be better to use Invoke Unity instead of CSharp to make it more simple and the code more readable.
Invoke C# is not what you want to use, you don't even understand how to use it
At first, I was using C Sharp Events, but someone told me to use Invoke Unity instead.
if you had PlayerInput in C# events mode I almost certainly assure you it was not necessary and you weren't doing it properly.
When it's in invoke C# events mode it gives you these events:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/api/UnityEngine.InputSystem.PlayerInput.html#UnityEngine_InputSystem_PlayerInput_onActionTriggered
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/api/UnityEngine.InputSystem.PlayerInput.html#UnityEngine_InputSystem_PlayerInput_onControlsChanged
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/api/UnityEngine.InputSystem.PlayerInput.html#UnityEngine_InputSystem_PlayerInput_onDeviceLost
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.8/api/UnityEngine.InputSystem.PlayerInput.html#UnityEngine_InputSystem_PlayerInput_onDeviceRegained
if you were using anything besides these, you were basically doing something very different
almost nobody uses C# events mode
Its all way more complicated than I ever expected.
I think you're just overcomplicating it in your head
this is all you need to do:
public void FullscreenToggle(InputAction.CallbackContext ctx) {
if (!ctx.performed) return;
// do the rest of your code
}```
then reassign the functioin from the inspector in the dynamic list, and voilka
I try to avoid code, that I dont understand.
the CallbackContext simply tells you some more information about the input that's happening
there's three phases:
started - the interaction started
performed - the interaction was performed
canceled - the interaction was canceled```
for a normal button press you'll get started and performed when the button is first pressed, then canceled when it is released
the behavior depends on the interactions you set up on the Input Action
It seems out-of-place to have all three of them executed (by default) why not a "performed" behavior included by default, if you did not wrote any CallbackContext in the script?
In what situation would it be usefull to have all three of them (by default) noticed?
Hey I didn't write the system
just telling you how to use it
I understand it. I'm just wondering why Unity don't replace the property that executes the code 3 times with "performed" (by default).
they want to give you maximum flexibility
I'm having some trouble with setting up rebinding that's specific to an input type (ie. controller vs keyboard).
Right now I've got a method:
private void PerformInteractiveRebind(InputAction action, int bindingIndex, bool allCompositeParts = false)
{
playerInput?.currentActionMap.Disable();
rebindOperation?.Cancel();
void CleanUp()
{
Debug.Log("We desposed of the action");
rebindOperation?.Dispose();
rebindOperation = null;
}
if (isControllerLayout)
{
Debug.Log("Controller layout was enabled");
rebindOperation = action.PerformInteractiveRebinding(bindingIndex)
.WithControlsExcluding("<keyboard>/anyKey")
.OnMatchWaitForAnother(.3f)
//.WithCancelingThrough("<Keyboard>/tab")
.OnCancel(
operation =>
{
RebindStopEvent?.Invoke(this, operation);
rebindOverlay?.SetActive(false);
//UpdateBindingDisplay();
CleanUp();
})
.OnComplete(
operation =>
{
playerInput.currentActionMap.Enable();
Debug.Log("Changed binding to " + operation.selectedControl);
rebindOverlay?.SetActive(false);
RebindStopEvent?.Invoke(this, operation);
//UpdateBindingDisplay();
CleanUp();
UpdateUi();
// If there's more composite parts we should bind, initiate a rebind
// for the next part.
if (allCompositeParts)
{
var nextBindingIndex = bindingIndex + 1;
if (nextBindingIndex < action.bindings.Count && action.bindings[nextBindingIndex].isPartOfComposite)
PerformInteractiveRebind(action, nextBindingIndex, true);
}
})
.Start();
}
else if(!isControllerLayout)
{
Debug.Log("Controller layout was not enabled");
rebindOperation = action.PerformInteractiveRebinding(bindingIndex)
.OnMatchWaitForAnother(.3f)
//.WithCancelingThrough("<Keyboard>/tab")
.OnCancel(
operation =>
{
RebindStopEvent?.Invoke(this, operation);
rebindOverlay?.SetActive(false);
//UpdateBindingDisplay();
CleanUp();
})
.OnComplete(
operation =>
{
playerInput.currentActionMap.Enable();
Debug.Log("Changed binding to " + operation.selectedControl);
rebindOverlay?.SetActive(false);
RebindStopEvent?.Invoke(this, operation);
//UpdateBindingDisplay();
CleanUp();
UpdateUi();
// If there's more composite parts we should bind, initiate a rebind
// for the next part.
if (allCompositeParts)
{
var nextBindingIndex = bindingIndex + 1;
if (nextBindingIndex < action.bindings.Count && action.bindings[nextBindingIndex].isPartOfComposite)
PerformInteractiveRebind(action, nextBindingIndex, true);
}
})
.Start();
}
// If it's a part binding, show the name of the part in the UI.
var partName = default(string);
if (action.bindings[bindingIndex].isPartOfComposite)
partName = $"Binding '{action.bindings[bindingIndex].name}'. ";
// Bring up rebind overlay, if we have one.
rebindOverlay.SetActive(true);
if (rebindText != null)
{
var text = !string.IsNullOrEmpty(rebindOperation.expectedControlType)
? $"{partName}Waiting for {rebindOperation.expectedControlType} input..."
: $"{partName}Waiting for input...";
rebindText.text = text;
}
}```
This method triggers whenever a rebind button is pressed, and I pass the necessary values to rebind that.
However, if the isControllerLayout is enabled, I get an error that says a rebind operation is currently active, but it still lets me rebind I just don't get the overlay or text to trigger -- though the rebinded button no longer works at this point because it gets stuck waiting for a button to be pressed. If isControllerLayout is disabled, everything works perfectly fine and as expected.
It seems like I might be using .WithControlsExcluding("<keyboard>/anyKey") incorrectly, as that's the only difference between the two?
I think I'm completely blind... but how exactly do I call a method repeatedly while a button is held? (I'm using the new input system)
Use Update if you wish to do something every frame
Hello, how do I detect the back button press on a phone and the swip (using the input system)??
How would I detect the release of a button from a CallbackContext? context.canceled is giving me false. I'm getting performed callbacks on press and release, I want to tell which is which
what interactions do you have defined on the action and/or binding(s)?
You should remove any that you have
that will leave you with the default interaction, which will do started/performed on press, and canceled on release
I am not entirely certain what a pass through is, but that seems to make sense
it felt wrong to have to check !isPressed to subscribe to a release event
pass through just always gives you a performed with the new value of the control for any change
basically it doesn't do the whole interaction thing
Ah, okay
am I supposed to be using WasPressedThisFrame? What was the point of my input mapping, then? 🤔
the inpuit mapping creates the action that you can call IsPressed() on
you can also use the events to set a bool true/false and read that
you're massively overcomplicating this
I wouldn't know, I'm just very confused lol
the way most people handle this is a Vector2 composite bound to a single action. Then you just have something like:
Vector2 moveInput;
void OnMove(InputValue iv) {
moveInput = iv.Get<Vector2>();
}
void Update() {
Move(moveInput);
}```
that would be for SendMessages mode
for unity events you'd have something like
void HandleMove(InputAction.CallbackContext ctx) {
moveInput = ctx.ReadValue<Vector2>();
}``` and otherwise the same
Oh, cool. Thank you
I have a problem with the event systems.. When I switch from MultiplayerEventSystem to the regular EventSystem, the EventSystem will execute the last action executed by the MultiplayerEventSystem (e.g. a pointer click). I have no idea why this happens.
I've tried switching the event system in a later frame, it still repeats the action, even 100 frames later.
We've had this issue before with other actions as well, but I never dug too far. However, it's becoming a problem now that we have multiple screens with close buttons are on top of each other: when you click and then switch event system, it actually closes two windows instead of one.
the switch is done like this, simply
foreach(var multiEventSystem in _multiEventSystems)
{
multiEventSystem .enabled = !bSingle;
}
_eventSystem.enabled = bSingle;
I've also tried adding a frame delay between deactivation of the multi event system and activation of the regular event system, but it still sends two pointer clicks 😦
I've found a "solution"! After enabling, if I disable and enable the input module, the double click doesn't happen.
_eventSystem.GetComponent<BaseInputModule>().enabled = false;
_eventSystem.GetComponent<BaseInputModule>().enabled = true;
I've got an issue trying to read a gamepad left analogue stick. Well, the reading part is fine but I'm using Unity Events and it's only firing once when the stick is moved rather than all the time. I've tried the Action Type set to Value and Pass Through. I've tried Control Type of Stick and straight up Vector2. It doesn't seem to matter if I have any Interactions setup (Hold or otherwise). Reading the phase, it seems to go through the correct sequence (Started->Performed->Cancelled)
Use Update if you wish to do things every frame
The input system is for informing you about input, not for driving gameplay code execution
So what's the prescribed method for reading an analogue stick's state if it isn't Events?
You can use events just fine
Save the current value in a variable
Use that variable in Update
Alternatively, just read the input value directly in Update and skip the events
Up to you
So Events are clearly a bust for me in this context. It happily sets the variable which I can reference as much as I want in Update... BUT, the variable doesn't change as the analogue stick changes.
So how does one read the input value directly?
Right - ignore me. I think I've found a raft of tutorials
I'm having issues with my movement for unknown reasons. Whenever I hold a key and release it, the character moves for a little while longer. The longer I hold a key, the further they "float" afterward. Issue is only with a keyboard. Controllers work perfectly.
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalInput, verticalInput, 0f);
movement.Normalize();
player.transform.Translate(movement * moveSpeed * Time.deltaTime);
}
I've asked my peers, I've asked ChatGPT, I've searched the internet. Normalize seems to cause it for some reason.
it's because you're using GetAxis
you should use GetAxisRaw instead
GetAxis applies some automatic smoothing
I also recommend movement = Vector3.ClampMagnitude(movement, 1); instead of movement.Normalize();
I'll check it out. Thanks!
i gave a gameobject the button component and still cant click it
Do you have an event system?
i fixed it, but still, thanks
Ok
I am trying to add support to PC users with keyboard using the new input system using the Send Messages behavior
The joystick for android support work perfectly but the keyboard doesnt...
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Player_Movement : MonoBehaviour
{
public float horizontal;
public float vertical;
private Rigidbody2D rb;
public Joystick joyStick;
[SerializeField] private float speed = 0f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Update()
{
// FOR ANDROID SUPPORT
//Move Right And Left
horizontal = joyStick.Horizontal;
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
//Move Up And Down
vertical = joyStick.Vertical;
rb.velocity = new Vector2(rb.velocity.x, vertical * speed);
}
//FOR PC SUPPORT
private void OnMovement(InputValue inputValue)
{
rb.velocity = inputValue.Get<Vector2>() * speed;
}
}
i called the function OnMovement like the SendMessage() displays
the values from a button press drop towards 0 over a small period defined by the gravity on the axis, by normalizing the movement you were scaling those small values back up 1
Hey I was just wondering how to switch the control scheme at runtime. I tried using SwitchCurrentControlScheme() but it keeps throwing me a null reference
Nvm I got it working
Hi, I'm not quite sure if this belongs to this channel because most questions here are about movement input whereas mine is like text input. I still hope its okay.
So I am currently working on a WebGL build which should be playable on mobile and desktop browsers. But now I ran into a problem that the keyboard won't show up on mobile devices when I click into an input field. Do I have to make a on screen keyboard myself or is it somehow possible to get the devices keyboard to show up and enter text into an input field?
This is a #📲┃ui-ux question
however AFAIK WebGL is not officially supported on mobile devices
so it's not surprising you're running into issues.
https://docs.unity3d.com/Manual/webgl-browsercompatibility.html
Unity WebGL doesn’t support mobile devices. It might work on high-end devices, but current devices are often not powerful and don’t have enough memory to support Unity WebGL content.
Oh okay thanks. Then I will probably make it support for desktop only if it's too hard to do. And sry I missed the channel earlier when searing for the right one 😓
If i disable an InputActionMap() and then re-enable it, all of the keys that were held when it was disabled will continue to be held when re-enabled until that key gets pressed again
is there a way to release all of the currently held keys on an InputActionMap to prevent this?
I've got a scene where the left thumbstick only has forward/backword functional (left/right does nothing). It's possible that the following error would help resolve but I don't know what it means:
Library\PackageCache\com.unity.inputsystem@1.2.0\InputSystem\Plugins\UnityRemote\UnityRemoteSupport.cs(284,49): warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'
ftr, the scene is being used in VRChat.
it would come down to how you set up your input handling and/or your code
that warning is irrelevant
Still no solution to this
Is there at least a way that i can release all held inputs on an inputactionmap
or deactivate an inputactionmap without causing all currently held inputs to get stuck
I've not setup or changed anything surrounds input handling. no code written either... it's a fresh project and fresh scene.
in a fresh project and fresh scene, there will be no scripts, no input handling, and no behavior or anything happening whatsoever
Do json files work on android? Also can you save images someway to a prefab or anything to save the image a user inputs from their android phone?
Should i be using web requests? Or is there a path for the json file on android builds?
what does "do json files work on android" actually mean? JSON is just a data format.
anything to save the image a user inputs from their android phone?
You can save a file on the device if that's what you're asking.
https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html if you want a location on the device to read and write files at runtime
Does anyone have experience with programming a control mapper menu for the new Input System?
Can I target specific controls and remap them easily through code? I don't have much experience with the new input system.
Google hasn't turned up many results.
Thanks very much!
Not sure if it's been asked here before or not but I want to incorporate rebinding with the new input system but the way I have seen to accomplish it is not ideal in my eyes I rather not use magic strings for the maps I rather have a concrete implementation that uses the generated c# input actions class
I have one editor in which I edit a List from the base class, and accessing it through a SerializedProperty correctly sets up undo and redo.
I have another editor for which the base class has a List of objects, which in turn have a List like the one from the first editor base class. This time I have to access the second list by using FindPropertyRelative(). This seems to break the undo and redo system, because I can't undo/redo the elements in that list. Is there something I need to add?
oh sorry
Can anyone help me with this bug I'm suddenly getting when trying to connect an xbox controller to Unity?
<RI.Hid> Failed to get preparsed data: The operation completed successfully.
My Steam App ID is set correctly
Also this is returning an empty string:
Debug.Log(Input.GetJoystickNames()[0]);```
(But GetJoystickNames.Length is 1)
And it was working about a week ago when I was last testing controllers
And the controller is connecting to Windows & Steam just fine
Also I've never seen an error have the words "completed successfully" before lmao wtf?
I'm getting the same error with a pro controller as well. Possibly an error in Steamworks?
If I turn on Steam Input in Steamworks and Steam Settings then inputs are going through but it seems to rebind each key of the controller to a keyboard key. Not useful
But then if I turn it off then no inputs go through
Pfft ok I'm completely stuck. I don't know how I progress from here. Is there a way I can start opening up Unity/Steam/Windows Devices and see behind the scenes/into the memory to try and find the root cause? I really need a nudge in any direction
Strangely it returns an empty string even when there's no controllers connected
Fuck me, restarted Unity for like the 5th time (And restarted Unity Hub this time) and suddenly started working
Yeah I'm glad I don't have to touch Unity again after I finish this project
is it possible to change the target dpi on runtime in mobile?
Unity 2021.3.1f1, using new Input System.
The same button that selects an upgrade from a menu also uses the player's active ability.
When the player selects an upgrade and the game unpauses, the player uses their active upgrade. I don't want choosing an upgrade to also use an ability the instant the game is unpaused.
When the upgrade menu is active, an upgrade control scheme is set. When the upgrade is chosen, the gameplay control scheme is set. It seems like a single button press is being used in both control schemes in the same frame.
What's the recommended solution?
I've implemented the Rebinding Action UI via the examples. The UI works perfectly, however, the user controls are not being properly rebound (and the input only responds to the old inputs). Does anyone have experience with this?
Is there a simple way I can find out what control scheme a InputBinding is part of?
I could probably hack a way using LINQ and madness but it would be preferable if there was a normal way
Found it, its InputBinding.groups
solved this using a coroutine to wait .1s before reenabling the gameplay action map, feels jank but it works
The overrides aren't applying to the controls, but everything about the rebinding works visually, with no bugs or errors. Any ideas?
I think I found out why the overrides aren't applying but I'm in someone else's code base and am trying to troubleshoot
The controls the player is using are from the custom C# class generated, I believe
but the input rebinder is targeting the inputactionasset
what's the best way to reconcile this difference without redoing a very involved character controller
I think this is likely why the rebound controls are reflecting properly on the UI but not on the character
Is there a way to derive the UserControls wrapper from the InputActionAssets, or apply overrides to the instanced class?
If I could have the RebindActionUI element target the UserControls here that would help, but I think that would take a big overhaul? The other thing I could think of would be not using the WrapperClass, but we were intending to support local multiplayer, and having localized controls is important. Any ideas?