#🖱️┃input-system
1 messages · Page 6 of 1
Yeah should be
it worked thanks alot!
No prob 
Hi i have got a question, i am very new to unity and im trying to make a cool 2D pixel game, however i finally want to do the attack animation and the attack itself, i already animated it and it looks good, but now, i dont know how to make it, that everytime i press fire it does the animation in the direction i am looking rn. Could anyone help me please? I´ve been trying to find a solution for 2 hours now.
https://www.youtube.com/watch?v=7vMHTUwtyNs this might help?
In this video I will show you how to create a simple melee combat in Unity so that you can perform an attack, detect all the enemies in range and reduce there through a custom health script.
Learn How to make a Juicy 2D shooter in Unity: https://courses.sunnyvalleystudio.com/
Aiming at mouse: https://youtu.be/DPqc7qYDtzM
New input system: htt...
literally anything you want from the new input system
I do not know what that would be
since i followed a guide with scripts etc for a camera
that was outdated
now someone told me to use a cinemachine
which i did
and when i put the cinemachine to follow my player
i get this
and i do not know
what I can switch it out for
All I can say is - find some new input system tutorials and learn how to use it
Cant you say another class then the one i was using?
that's not how it works
^
otherwise switch back to the old input sytem
if you don't want to learn the new one
the answer is actively try to learn
do you know a video that can help me get what im trying to learn?
Unity has a tutorial on their YouTube channel for the new input system
Thank you
what are you trying to learn
I am trying to what class it is that i have to swap out Input class for
ok and like I said before it's not that simple.
do what osteel said
ive looked for it
cant find it
so il just watch
anoter video
i see one by code monkey and brackeys
but not one by unity
How do i fix this
Does anyone know how i should code it, that when my character moves and then stops, that he s still looking in the direction he went to ?
Is there a way to do PerformInteractiveRebinding on composite bindings in newer (currently using 1.1.1) versions of the inputsystem?
Hey im trying to make my fisrt ever game, and whatched a tutorial. but i cant seem to find the problem
did i do something wrong, im trying to get the camera working
What year was the tutorial made in?
Because I don’t know much about coding but they’ve updated the control system in unity
I think…
No, they just didn't follow the tutorial correctly.
There are countless issues with this (I count at least 11). You need to follow the tutorial properly, including paying special attention to the spelling and capitalization.
If your IDE isn't giving you auto-fill/correct, then you need to also configure it using the instructions in #854851968446365696. Some of those spelling mistakes should be near impossible with a properly configured code editor.
You did axally, not.
If you did, it would have worked. Start by configuring your IDE please.
On the new System, I can't figure out how to rebind a composite binding. I'd like to use ApplyBindingOverride(), but I can't cause it needs an action.
I tried to look at ChangeCompositeBinding, but I don't understand what it does. It returns an InputActionSetupExtensions.BindingSyntax which I don't know what I'm supposed to with.
I can't just do binding.overridePath = path why would be very handy but it's readonly.
Help 😦
The whole InputSystem seems so awkward to use in code...
So... I have some experience with this... replying to something somewhere else right now.
Also I'd like not to use PerformInteractiveBinding cos I already use it for the movement of another action map, and want to change the movement of other action map at the same time.
I tried figuring out a way to instantly complete the interactive binding but I don't know how to feed it the path.
I kinda regret using this system tbh, it looks great in editor and easy to setup, but changing bindings and finding their names is so awkward. It's like problem -> 2h of reading through cryptic documentations -> an exception -> 2h of reading through cryptic documentations -> an exception -> ... T_T sry need to rant
I personally love it, but there are a couple major parts that aren't accessibly documented.
I mean why would ApplyBindingOverride be called on an action instead of, well, a binding
Regarding composite bindings, there is no way to get a collection of all actions belonging to a composite except for iterating through all the bindings in the asset and checking .isCompositeBinding == true in serial. I'm not sure if that's the member- I have to look it up.
So the problem is this : you don't get a collection of actions, you get a collection of bindings
And I can't do anything with bindings
You can access its path, but can't override it
I appreciate that you try to help tho, don't get me wrong ^^ thanks
I'm looking through some production code to see if I can find a solid concise example. @charred wagon
Seriously tho, first result when I type ChangeCompositeBinding is one that uses PerformInteractiveBinding, second is the doc, and third is some dude ranting about it on Twitter. Then it's in chinese ><'
"unity's new input system is the most "unity need to actually make a game before they make systems" thing I've ever used"
Can't say I disagree with him tho
InputAction action = InputActions.asset.FindAction("actionName");
So first of all, I grab the action that I want via it's string name like this. This always grabs from the asset itself and not a clone if you use C# events or something, which actually doesn't allow editing of the original asset as the C# bindings don't see the actual asset after code generation. I always use C# events.
{
var firstPartIndex = bindingIndex + 1;
if (firstPartIndex < action.bindings.Count && action.bindings[firstPartIndex].isComposite)
RebindAction(action, bindingIndex, onRebindComplete, true, excludeMouse);
} else
RebindAction(action, bindingIndex, onRebindComplete, false, excludeMouse);```
This is how I read through the bindings on that action. If they are composite, then I get an equal number of "RebindAction" invocations for that number of bindings in the composite action.
What's RebindAction?
RebindAction() in my case is quite long and controls a user experience that uses interactive binding, but the code above shows how you separate out separate binding calls to set multiple bindings on a composite action.
I'm pretty sure what I need is within that
I know how to access the bindings, I don't know how to change them
{
if (actionToRebind == null || bindingIndex < 0)
return;
bool reenableLater = actionToRebind.enabled;
if (reenableLater)
{
actionToRebind.Disable();
}
var rebind = actionToRebind.PerformInteractiveRebinding(bindingIndex);
rebind.OnComplete(operation =>
{
if (reenableLater)
actionToRebind.Enable();
rebind.Dispose();
if (allCompositeParts)
{
var nextBindingIndex = bindingIndex + 1;
if (nextBindingIndex < actionToRebind.bindings.Count && actionToRebind.bindings[nextBindingIndex].isComposite)
RebindAction(actionToRebind, bindingIndex, onRebindComplete, allCompositeParts, excludeMouse);
}
SaveAllBindingOverrides(actionToRebind);
onRebindComplete?.Invoke(actionToRebind);
rebindComplete?.Invoke(actionToRebind);
});
rebind.OnCancel(operation =>
{
if (reenableLater)
actionToRebind.Enable();
rebind.Dispose();
rebindCanceled?.Invoke();
});
rebind.WithCancelingThrough("<Keyboard>/escape");
if (excludeMouse)
rebind.WithControlsExcluding("Mouse");
rebindStarted?.Invoke(actionToRebind, bindingIndex);
rebind.Start();
}```
This causes the interactive binding experience to repeat for the right number of composite bindings within the action.
Of course this will only help if you want to use interactive binding.
Right, I figured that out. The thing is that I have several action map with different "move" actions that are composite.
I want to change the bindings of all "move" actions at once, else it's very awkward to have the player remap for every action map
if (reenableLater)
{
actionToRebind.Disable();
}```
About this part: you must disable an action before you can write to it's bindings, else it'll do nothing. @charred wagon
Yeah I mean everything you do I found a way to do it.
{
operation = playerInput.FindAction("Move").PerformInteractiveRebinding().WithTargetBinding(0).WithExpectedControlType("Button").WithControlsHavingToMatchPath(controls).OnComplete(callback =>
{
rebinding = false;
StopChangeInput("MoveUp");
}).Start();
}```
That's what I do, found that on a forum
Problem comes when I want to apply that change to bindings in other action map without having to do the whole PerformInteractiveRebinding
Is there a way to feed the path to that medthod?
I think inside OnComplete(callback => {}); you want to add operation.Dispose() or the system might possibly misbehave.
It's in StopChangeInput()
I'll look in the docs.
There's a coroutine I start which stops the rebinding after 5 sec in case the user does something stupid like try to rebind a binding for the PS4 without a controller aha
Cos otherwise it's gonna wait for an input of PS4 with all action maps disabled infinitely
Thanks, I couldn't find much about it. There's a load of methods that comes with it like Complete(), OnComplete(), etc... which aren't documented anywhere. It would be very handy to just simulate the input pressed and do Complete() so it's all done in one frame
Have you looked into InputAction.ChangeBindings(), in UnityEngine.InputSystem.InputActionSetupExtensions?
Yeah I saw that, there's also ChangeCompositeBinding, I just have no idea what it does
I think the only thing it does is that it returns a InputActionSetupExtensions.BindingSyntax
And idk what to do with that
Hooo there's something I didn't do yet, maybe I can destroy the whole composite and reconstruct it
God this is desperate
Probably my best bet tho. If I knew beforehand I would have constructed the whole thing through script lmao
.With("Up", "<Gamepad>/leftStick/up")
.With("Down", "<Keyboard>/leftStick/down")
.With("Left", "<Keyboard>/leftStick/left")
.With("Right", "<Keyboard>/leftStick/right");```
Seems easy enough, just need to find how to remove composite bindings
.With("Down", "<Keyboard>/leftStick/down") Lmao the infamous keyboard left stick
wat
Just to be clear- is this to override an existing binding or build it originally through code?
That's the docs, do they actually test this stuff? O.O
No idea, it's probably to build it through code, and there'll be no way to remove it
Obviously the only method there is RemoveAction() which isn't documented. and there's no AddAction()
It seems that adding actions is totally protected by the InputActionAsset.
Ah! I found it!
var asset1 = ScriptableObject.CreateInstance<InputActionAsset>();
var actionMap1 = asset1.CreateActionMap("map1");
action1Map.AddAction("action1", binding: "<Keyboard>/space");```
From the docs: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.InputActionAsset.html
var map1 = new InputActionMap("map1");
var map2 = new InputActionMap("map2");
asset.AddActionMap(map1);
asset.AddActionMap(map2);
var action1 = map1.AddAction("action1");
var action2 = map1.AddAction("action2");
var action3 = map2.AddAction("action3");
// Search all maps in the asset for any action that has the given name.
asset.FindAction("action1") // Returns action1.
asset.FindAction("action2") // Returns action2
asset.FindAction("action3") // Returns action3.
// Search for a specific action in a specific map.
asset.FindAction("map1/action1") // Returns action1.
asset.FindAction("map2/action2") // Returns action2.
asset.FindAction("map3/action3") // Returns action3.
// Search by unique action ID.
asset.FindAction(action1.id.ToString()) // Returns action1.
asset.FindAction(action2.id.ToString()) // Returns action2.
asset.FindAction(action3.id.ToString()) // Returns action3.```
I can't seem to be able to remove it tho
It works in a vacuum maybe it doesn't pair well with the rebinding ending on the same frame idk
Thanks a lot btw I was going crazy trying to do that
I think... you can use InputAction.RemoveAction(). As I understand, this orphans the action from all associated InputActionMaps.
Yup, I can't use AddAction on my action map tho
Really? What's the issue there?
Nor can I do AddActionMap for that matter
Maybe cos I generated it through script?
Yeah it does some weird stuff when I look at the generated code
Does your action map belong to an asset? Even if that asset was itself instantiated through code?
I don't know, how would I know that?
var asset = ScriptableObject.CreateInstance<InputActionAsset>();
You need to get a reference to an asset, to then be able to add the action map to it.
This is assuming that you are just setting it up through code.
Yeah that's the thing I'm not I made it in inspector and generated a code with it.
Then I do playerInputActions = new PlayerInputActions();, PlayerInputActions being the script that's generated
Okay, are you using the C# event hooks?
Yup
playerInputActions.asset.FindActionMap("UI").AddAction("Move");
Maybe that works?
I didn't see I could access the asset directly there
Okay, one major headache I always had was with the input system was the asset reference getting constantly cloned, so I was getting references to the active in-memory asset, but I was unable to actually alter it persistently. InputAction action = InputActions.asset.FindAction("actionName"); really saved me here, because this line gets me the reference in the original InputActionAsset that you create in the GUI. If you try to reference the actionmaps from your new InputActions(), you'll never be able to write changes to the original since you're just seeing a deep copy.
Yeah, this was why I mentioned it like very first thing... that line resolved so many issues for me.
InputActions is my generated class. InputActions.asset lets you get to the original ScriptableObject which you edit in the editor. Anything else is a deep copy made when you instantiate InputActions.
All good - that was the first massive headache that I stumbled across. The second one was the nature of how compositebindings are packed together.
I'm having a hard time understanding what you said.
What are you doing differently exactly? How do you use the inputs, not with events? @blissful lotus
There's this SaveBindingOverridesAsJson, Doesn't this make the change persist? Or do you mean that you have to load it everytime
So I do this :
playerInputActions.UI.MoveUI.canceled += ctx => StopScroll();
But your do this :
playerInputActions.asset.FindAction("MoveUI").performed += ctx => StopScroll();
Is that correct?
Yeah, that should work. I tuck that part up to FindAction in a helper method, myself.
So if I do PerformInteractiveRebinding on the action of the asset rather than the one of the generated class, it will persist?
Exactly this 100% as long the other stars all line up as well. But this is a requirement for it to persist.
So you completely bypass the generated class?
Sorry I'm having troubles wrapping my head around this I'm not that comfortable with coding ^^
The input system actually uses a ScriptableObject, and the generated class is just a copy of it that's supposed to be used instead? Is that how it works?
How is the change persistent then? How is it saved? I don't get that
You actually change stuff in the game's directory rather than saving it in a external text in Json like it's intended?
private static string BuildActionStorageKey(InputAction action, int bindingIndex)
{
return action.actionMap + action.name + bindingIndex;
}```
This doesn't have a good permanent repository set up, but this is how I store the bindings in PlayerPrefs.
{
InputAction action = InputActions.asset.FindAction(actionName);
for (int i = 0; i < action.bindings.Count; i++)
{
if (!string.IsNullOrEmpty(PlayerPrefs.GetString(BuildActionStorageKey(action, i))))
action.ApplyBindingOverride(i, PlayerPrefs.GetString(BuildActionStorageKey(action, i)));
}
}```
How do you apply the binding override to the composite bindings tho?
Also I'm looking at the generated class and it's crazy how easy it is to modify the JSon file directly and how clumsy the methods are to modify it.
And access it
What in the hell
action.bindings just has the separate bindings listed in serial. Something with 4 bindings will take 4 elements in that list.
Not how I would have designed it, either.
Wait that's what I wanted to begin with lmaooo
AHahaha
Ho god
I did say this at one point... ugh...#🖱️┃input-system message
Before I actually looked at the API, this was my attempt to explain that.
Holy I'm so sorry T_T I didn't understand what you meant by that
Okay, I wasn't exactly dialed into the conversation yet, I see.
I mean I learnt A LOT about how the whole thing works don't get me wrong
Yeah, you have to keep checking the upcoming parts when you know you're reading a composite. You keep rolling through the bindings until you've settled all the entries for your composite action.
Sorry, I thought I was a bit more coherent at the time, but I couldn't remember the API at the start of the convo either.
Since action.binding[someIndex].action returns a string for some reason I assumed that composite didn't have action
That they were just part of the "parent" action if that makes sense, cos I found no way to access them. I still don't know how to access them, but at least I can change the binding directly.
Alright, I'll try to get that to work before going to bed. Thanks a lot man, I really appreciate it.
(In EU so it's getting pretty late)
It works very well and is non-polling, but it's a lot to learn. I pretty exclusively access everything from the top using asset.FindAction("map1/action1");
It's consistent at least.
God I hate myself, I must have seen that part about the index in ApplyBindingOverride but I must have looked at docs for like 4 hours today and my brain stopped working I guess
The docs for this look like a kaleidoscope of "Input", "Action" and "Binding" arranged in unending permutations. It also doesn't help that a lot of functionality is locked up in type extensions.
I know right T_T I thought I'd go mad before making it work aha
Anyway, thanks again, love the help.
See you
Everything's working like a charm, ❤️
Yeah, the C# event implementation does a number with it's cloning of the asset in memory.
I was wondering, do you create different objects of the same PlayerActions in different scripts? Cos that maybe why you have stuff changing, if you change one it won't apply to others. I only ever use one that's in a singleton and I had no problem so far, so that's why I thought of that.
If you reference the asset.FindAction(), it doesn't matter. This is a paradigm that only applies when you use the generated C# class.
Yup, cos they all use the same asset
Makes sense
It's sorta complicated of an answer, because sometimes you do get the object back. If you disable an action and try to reference it certain ways, you'll get a new instance. You can see this happen in the input debugger.
Ho damn ok, makes sense to use the asset then.
Hello guys, something weird happened to me. I am using the old input system and I loaded the top down engine asset, which added a lot of inputs to my project settings. No problem there. The thing is, I needed to tweak a couple inputs but in order to find out the correct settings I kind of tweaked stuff blindly.
Curiously after finding out the correct settings I somehow ended with an extra 12 inputs that are used for debugging... Does someone knows about this?
if i want to make the number keys switch between different tabs, would it be better to add different actions for each key or one action that takes all keys, and then somehow check which key is being pressed? if the latter is better, how do i check which key is being pressed?
different actions
gotcha ty
does input system play nice with 2022.2?
trying to double click to setup bindings and nothing is happening
That is the version I am using and it works fine.
Question. I an trying to call Mouse.Current but it is returning null. I have an instance of InputActions that is enabled, is there anything else I need to do? Do I need a physical mouse or does a track pad work?
Weird...
You need a physical mouse I believe.
Though laptop track pad should qualify iirc 🤔
i wonder if its cause of Entities 1.0 breaking stuff
oh well i'll just hack around this
don't technically need the editor...
strange I just attached a mouse and still getting the error. Anyone else have any idea how to track it down?
looking into the new input system how do you do "While action is held"?
can't seem to find anything good on google to explain it
Use Update
Or a coroutine
na i understand that part
but what do you call to check if something is continuously held for an action?
like i can find how to do it for a specific key
but not for a specific action
Look at the documentation for InputAction
There's IsPressed() etc
Okay Mouse.Current is null, but there is a mouse attached. Has anyone else had this issue? Nothing is coming up on google.
Well updated to 2022.2.0b16 and it is working again.
So im following this tutorial of 3d fps, what this and what is the solution?
may someone help
Has anyone gotten success with a razer kishi and the new input system? Everything else seems to work for me so far but this controller for my phone for some reason is only detecting the left stick of the gamepad.
Hey, how can I do something like this in the new Input System?
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.4/api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_IsPressed
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.4/api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_WasPressedThisFrame
Hey everyone, I got a bit of a noob question. I switched to the new input system and it's giving me a headache.
This is a snippet of my old code:
`public class SomeClass : MonoBehaviour
{
[SerializeField] private string Key;
void Update()
{
if (Input.GetKeyDown(Key))
{
Do Something
}
}`
This is what I was previously using and I want to use similar code but with the new input system. Anyone have any ideas on what I should do?
I have no idea how to use the variable with the new system
Generally people go with the event based approaches in the new system rather than polling
But if you want to poll in Update you can use these too
(from right above your post)
My bad, I wasn't sure if they'd allow me to use variables the way I needed them. Thanks! Will check it out, hopefully I'll get it to work 😄
Working on a really specific thing, event based would take a lot more time and effort (at least with my knowledge)
The new input system has a good built in way to do rebinding
You don't need to do a janky thing with a string like you have there to do rebinding in the new system
Also event vs polling is really not complicated to switch between
Idk I dont understand it
Could someone hop in a vc with me some time to go over some code? I really cant get it to function
I've personally found it to be hard to grasp making something like GetKeyDown with events, where you want an action to be able to repeat without needing to release/press the bind again
wait.... is setting a bool to true on press and setting it to false on release all you have to do
🤦♂️
then you'd need to run the code that checks for the bool in update
which defeats the purpose
i just start a couroutine when the hold input is started
probably ins't a very efficient way to do it but idk of any other way
- Is this error message common, or am i the only happy person to have it?
Have you googled it?
I've never seen that particular one from the input system
seems like a bug in the GUI somewhere though
- Various topics on custom fields / property drawers
- But nothing regarding the input system
- It refers to this line
well this seems to be an error in a custom field/property drawer which Unity wrote as part of the input system
- Well, should i report this?
Sure
- Okay, then tomorrow. Until then, any ideas on what happens here and why does it go wild?
what goes wild?
- Well, the system with its errors
my limited comp sci knowledge tells me that it's more efficient to check a bool value than it is to call InputAction.IsPressed() every frame
what I meant was keeping update method clear of input checks
I used to rely on a input bool in update but it quickly got messy the more hold buttons you add
I guess it's fine if you'll only ever have 1 or 2 buttons that edit a hold bool value
but it's a recipie for disaster
Hey, I ran into some problems with my InputActions. My script, does work with the _MovementMap & the _InteractionMap but not the _ShootingActions. I can access the _ShootingMap.
Like I said, it does find the map and every other Action works, except the ones in the ShootingMap. AND I DONT KNOW WHY.
I did everything the same.
If you have any comments, ideas or whatsoever please help me. I published the full script here: https://gdl.space/etozecuqih.cs
Here are some screenshots and a (I hope relevant) part of my Script.
//Connect _action with ActionMap.FindAction("")
_MovementMap = PlayerInput.actions.FindActionMap("Movement");
_InteractionMap = PlayerInput.actions.FindActionMap("Interaction");
_ShootingMap = PlayerInput.actions.FindActionMap("Shooting");
//movement
_moveAction = _MovementMap.FindAction("Move");
_lookAction = _MovementMap.FindAction("Look");
_runAction = _MovementMap.FindAction("Run");
//interaction
_PickUpAction = _InteractionMap.FindAction("PickUp");
_InteractAction = _InteractionMap.FindAction("Interact");
//inventar
_InventarL = _InteractionMap.FindAction("InventarLeft");
_InventarR = _InteractionMap.FindAction("InventarRight");
_MouseInventar = _InteractionMap.FindAction("InventarMouse");
//Shooting
_ShootAction = _ShootingMap.FindAction("Shoot");
_ReloadAction = _ShootingMap.FindAction("Reload");
_AimAction = _ShootingMap.FindAction("AimLOL");
Thank you all for reading. Every Idea/Comment is welcome. I really appreciate!
Hi guys, I'm not sure if this is a bug or not. But Let me know if my implementation is correct.
I have a parent object (RotateIconContainer) that has a rotation script attached to it. The container has a child which is the rotation icon, which is positioned on an object, when the object is selected.
The issue i have:
When I used OnPointerEnter and Exit, these two function run when i hover over the icon entering and exiting. But when I use OnPointerDown, it doesn't fire. It only fires when I am over the red square, which is an image component I've placed on the parent object, which is at world zero.
Am i doing something wrong why OnPointerEnter and Exit fires on the icon, but OnPointerDown doesn't?
I needed to add an instance of the script to the icon. But the icon visibility does get switched off also. Which is why I didn't want to do that. But adding another instance to the icon for down clicks seems to work. But that doesn't explain why enter and exit works. Because I was surprised to see that they worked.
- I can't find any article in google regarding subscription to the system's events through the code. And okay, i know that it can be configured through the inspector, but i'd prefer adding listeners from script. Any docs on that?
✅ Get the FULL course here at 80% OFF!! 🌍 https://unitycodemonkey.com/courseultimateoverview.php
👍 Learn how to make BETTER games FASTER by using all the Unity Tools and Features at your disposal!
👇
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Gam...
You will get the basics on how it works from that
- I don't use this component because it causes some inconvenience to me, since it requires for me to add a random public method to my class where i check its phase and only then pass it down to the actual code. Instead, i want to get an SO that handles all the garbage and invokes actual events straight away. In the video it's mentioned that by default everything is disabled in the generated class instance. Is it also the case for the asset?
Not sure what you're looking for, but tell me if that answers it
I got a script that handles controls, I create an object from the class that's generated
playerInputActions = new PlayerInputActions();
And then you can subscribe either like this :
playerInputActions.someActionMap.someAction+= ctx => DoStuff()
Or
playerInputActions.FindAction("actionName") += etc...
Also if you want access to the SO, there's playerInputActions.asset which you can see in the generated script
(Obviously playerInputActions is the name of MY script, might be different for you)
Yes the input system scripting reference has everything about this
The idea is just getting an InputAction reference from your asset and then you can subscribe however much you wish to its events
- This still returns base action with its 3 states, and i still have to get context is
DoStuff()and filter it to be performed inside my actual code. This is a straight way to flooding my code with useless garbage, so i want to put these checks inside the SO, reference it to any script that requires it and use it as a "clean" input reader that invokes pre-made events i can easily subscribe to
- Now the problem is, subscribed methods don't listen to the system's actions. They pretend to ignore it
playerInputActions.someActionMap.someAction.performed
Maybe that's what you're looking for,
Each state has its own event trigger
- I know this, yeah. And i subscribe my methods to it in on enable, however nothing happens when i press keys. Is it appropriate to send my code here?
Did you Enable() on the action?
You need to activate it each time you want to use it
- Yup, i did after i watched the video. Still no luck
- In a moment
https://paste.ofcode.org/p9PMecBkiKPGrF9SCvgbi4, starting line 47
- If you also need an inspector screenshot, it's fine in there. All actions and maps are in place
- Oh, btw. After i added enable and disable lines, it throws 4 errors in a row at me
- All of them are from internal class of the system
Do you get the error if you do _InputAsset.Player.Enable() directly?
I don't need to find them personnally
I just do inputAsset.actionMapName.action
- It's not a script instance, it doesn't have
Playerstruct in it
- Oh, after i used find by name, it's gone
- Apparently my init logic is wrecked
Not sure if that's important, but maybe add = new InputActionAsset(); when you declare
- Now i'm curious why. Inspector says it's okay
- Unity doesn't think tho
Wait you're using the scriptable object, I have no idea what that will do actually
I use the generated class
Not sure you're supposed to access the SO, no idea tbh
- No, i use default asset. But it's treated as an SO
- Actually now that i execute init part regardless of any condition, it does work. So the only thing i missed was enabling and disabling
- It's okay now. Thank you for your effort
- I tried this and well, it tells me exactly this again. However after i move it to either start or awake, it's cool
Hello
I am using unity 2019.4.40f1, I added input system 1.3.0 to my project and made a .inputactions asset. However unity gives me an error that says
Failed to load 'Assets/ScriptableObject/PlayerActions.inputactions'. File may be corrupted or was serialized with a newer version of Unity.
I found that "Pass through" together with axis lets me use readValue<float>(). since it is really handy, I am tempted to use it all the time. Is there a disadvantage to this way of doing it? And if so, what is the better equivalent of it?
Regarding PerformInteractiveRebinding, when I finish rebinding, some inputs like controller triggers will be performed again when released. That's pretty annoying because if I rebind the button menu, since I'm in a menu, it will close it.
Although, when checking for action.performed with the same trigger, I get only one log, showing that it's performed only once (on button press, and not on release).
For now I have a coroutine that waits a bit longer before enabling the action map again, but I'd really like to know what's going on and how can I avoid that.
Anyone has had experience with this?
- To change active input map through script, i have to disable and disable them manually, or is there dedicated method for this somewhere?
I don't think there's any global concept of the "active" input map
PlayerInput has such a thing but that's specific to PlayerInput
so yeah you'd enable/disable as needed I think
- Oh, well. That's exactly where this wondering of mine originates from
- So if that's not the case, having all maps enabled is fine?
Sure
- What if both maps do have same actions? For context, one is used for player and
Escpauses the game, while second one is used for pause menu and continues from here. Will they overlap, and is it right to do this overall, or is it inconsistent with the concept of the system?
they will both trigger if both are enabled at once
- I see. Is there any article with tips on how to organise maps and actions?
Don't really like the new input system so I'm sticking with the old one for now. I know you can check for vertical and horizontal input in the left stick by doing Input.GetAxis("Yeah"); but is there a way to do it with the right stick?
I've had so many issues with the new input system honestly it just feels overly hard and it always snaps to exactly diagonal or vertical / horizontal. No in-between for smoothing or nothing
I'm having the problem, that my keyboard button that is mapped to an axis reads as "0.5f" until the button is pressed once, so it kinda initializes wrongly, but I found no way to properly set a default value // influence that. Is there more to that?
Okay this seems to be related to my composite binding of the steering wheel, that, even when not connected, causes 0.5 until I press the keyboard button (for whatever reason that changes things). Here, the absent wheel probably outputs "0", which is then inverted to "1" and then normalized to 0.5.
Can I somehow make it ignore non active bindings completely? My problem is that the axis will read "0" when it's pressed halfway
Edit: Apparently changing the order fixes it, but I'd still love to understand how it deals with composite inputs
There's more info about how it disambiguates multiple controls here:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.1/manual/ActionBindings.html#disambiguation
Should I use events (CallbackContext) or InputActions? or both?
Asking because I feel like there are features I can only implement by using .triggered or .isPressed() but it might screw the proper "workflow" for implementing the new input system
These two are intertwined and you will be using both in any case
If you're asking about polling vs events, use both as well, whichever is easier for each thing
I see, thanks!
Hey, quick question, how can I make it so that my player moves/rotates with my mouse. so when i move my mouse to the left, the player faces to the left with my mouse? This is all in 3d btw, thanks.
What is a simple way to check if an action is still being performed with the new input system? I have an action called "holdFire" with a interaction of Hold. In my code i refrence this with a "OnHoldFire()" function that is called by the Player Input component. But id like to be able to know when the button is released. or be able to check the state of the action. Example: return the value of an action to a variable and use an if statement to check if that value is equal to 0
does anyone know a good article about "standard" controller controls? ive basically never played anything on console but i want the controller controls to be familiar to people who have
for example what would be the expected button on controller to do something like open invnetory (tab on keyboard in my game)
use if ctx.performed and ctx.canceled
how do you assign ctx as an argument/variable? as in how do you link ctx to a specific input action?
mouseClick stop works while I playing
Also If I continue taps I can see that
Touch MouseClick only in OnEnable/OnDisable and didn't turn MonoGrabber off
Just stops working
Set stopPoint in SlotsDragPerform and it's not even called
how are you triggering your methods? if your using unity events make the method take a CallbackContext ctx as an argument and then click the dynamic version of it
i dont know the math term for this, but i need with the new input system how would i get something like the default new movement system, but the numbers like 1, for example in the vector2 it should be only 1 or 0 for each float, does that make sense, and how would i go about achieving it?
im also happy to try rounding the vector2 after i get it, if that will be easier
im so confused, the default movement system gives an opposite vector after each positive vector, meaning i have to move backwards after i move forwards and vice versa, what on earth lol
huh, it is randomised every play mode, some play modes pressing w gives me 1, othertimes 2, sometimes 1.5, uncertain why, consistent throughout the playmode session though
still getting the suck back vectors, so atleast that is consistent
here is my code, incase im doing something horribly wrong: ```cs
public void Move(InputAction.CallbackContext context)
{
var Movement = context.ReadValue<Vector2>();
float3 NewPos = new float3();
if (Movement.x >= Threshold)
{
NewPos.x = 1;
}
else if (Movement.x <= -Threshold)
{
NewPos.x = -1;
}
if (Movement.y >= Threshold)
{
NewPos.z = 1;
}
else if (Movement.y <= -Threshold)
{
NewPos.z = -1;
}
TryMove(NewPos);
//TryMove((float3)transform.position + new float3(math.round(math.round(Movement.x*Mul1)*Mul2), 0, math.round(math.round(Movement.y*Mul1)*Mul2)));
}
this is called normalization
this would depend heavily on your input action setup but... shouldn't be.
ah fascinating, thanks for the info!
is the whole mouse being at 0,0 in the first couple of frames normal?
var mousePosition = lookAction.ReadValue<Vector2>();
print($"Time: {Time.frameCount} Mouse Position: {mousePosition}");
In update
is that really an issue though?
Might be that the game isn't focused yet, I get the same behavior.
it doesn't happen with the old input system and I can technically code around it, its just weird
The phase seems to be waiting in those first updates.
phase?
ahh i see
this is a really annoying bug in input system in the editor where clicking the play button queues a couple mouse events up for the runtime to process
instead of saying time is your count, print the actual time property in the event. you'll see that it's negative
input system has BUGS
I would guess it's probably editor-only but yeh
using both a wired ps5 controller and wired nintendo switch pro controller i can only get one control scheme to work with the controller at a time. right now i have two, one for a cursor and the other for the camera.
If I leave this one the Any scheme then the controller inputs for this scheme work
but then the controllre inputs for this scheme do not work
actually I got that last part backwards. If I set the Camera to use the GamePad scheme by default then the camera then functions with the controller, but the cursor stops functioning with the controller
if I leave all settings default as Any and auto-switch then only the cursor controls work for the controller
setting the Camera controller to the gamepad scheme lets me still use the keyboard&mouse controls for the cursor though
really confused on this.
all the control actions have the enable and disable code setup
I set up a button action and i wanted it to only turn a bool true when key is pressed down but it doesnt work like that since if i hold the key the bool stays on true. Its purely input system, no other statements used.
how can i achieve it like i want it ?
- subscribe to the
performedevent - Check in Update for
WasPressedThisFrame()on the input action - If you have a CallbackContext check if it was
performed
thanks, i'll try that
I have a "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it." error in my script what i don't understand at all. this happens ONLY when im reloading the (async) scene?
at the blue arrow he has the object at the red arrow de object is null.
the strange thing is i don't ever set this value in script i set it only in engine [serializefield]
I don't use singletons in this so i know he doesn't have a reference to a old variable or something?
does someone know what there is wrong
i don't set the value in script and setted in the engine
You are talking about async, did you set a breakpoint to check, what is actually happening to your code? Where it turns null?
I checked this and everywhere is het a value except the last one
the last one is null but i dont set this variable in my code
this is litterly all my reference and it only happens if im reloading my scene
i try to load it not async but that didnt help same error
this is a way how i can make it work i don't get it why it's returning a null
@zenith mason Do you use the component or do you generate the c# code?
If you use the code, they might be some shenanigans at some point
you mean the player input component
Yeah
no
Right, so you do something like MyInputClass = new MyInputClass(); and then use it?
yes i do this inside the scriptable object
I didn't have problem with it, but if you do you should do myInputClass.asset.SomeMethod rather than myInputClass.SomeMethod
When you reach directly in the asset you'll modify the scriptable object directly
Otherwise you might make changes that are not persistent
It being a scriptable object is not really a problem besides that
yeah that what scare me at the moment I use resource.load instead of drag and drop
Personally I use the method to save input rebinds externally, works great
The scripting API is hell tho and you might take a while to figure out how to use the input system in code
SaveBindingOverridesAsJson()
Ho yeah one last thing, it's probably better to use one instance of the class in all your script so they are not competing, in a singleton for example
Howdy fellas, i could use a hand seeing im loosing my mind seeing the input system work on a previous project and not work on my current one
Coisa() just has a print in there nothing else
and im using the default inputActions given by unity
i just copied and renamed it
this worked fine on my previous project
i have the player settings for both input systems
I don't see a playerControl.Enable(); or click.Enable(); anywhere
thx, i looked over the other files a couple times managed to miss it, was going mad already
My inputAction isn't loading, and when I try to make a new one I get the fallowing errors.
InvalidOperationException: Failed to add object of type `InputActionAsset`. Check that the definition is in a file of the same name and that it compiles properly.
UnityEngine.InputSystem.Editor.InputActionImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) (at Library/PackageCache/com.unity.inputsystem@1.4.4/InputSystem/Editor/AssetImporter/InputActionImporter.cs:95)
UnityEditor.AssetImporters.ScriptedImporter.GenerateAssetData (UnityEditor.AssetImporters.AssetImportContext ctx) (at <d5cfe1b7a8b8455dae78439447671342>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
```Asset import failed, "Assets/Modules/GenericInputActions 1.inputactions" > InvalidOperationException: Failed to add object of type InputActionAsset. Check that the definition is in a file of the same name and that it compiles properly.
UnityEngine.InputSystem.Editor.InputActionImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) (at Library/PackageCache/com.unity.inputsystem@1.4.4/InputSystem/Editor/AssetImporter/InputActionImporter.cs:95)
UnityEditor.AssetImporters.ScriptedImporter.GenerateAssetData (UnityEditor.AssetImporters.AssetImportContext ctx) (at <d5cfe1b7a8b8455dae78439447671342>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
I can find the InputActionAssets.cs script in Packages/InputSystem/Actions. There is also no error in console on compile.
It is broken again... This is the third time something like this has happened, and I am getting tired of redoing everything.
And reinstalling the Input system package didn't fix it this time.
Seems to be an issue for a while that still isn't fixed.
Uploading a bug report, there goes my night.
Hello,
I do have a question concerning the Player Input Component with Unity Events.
I am changing the action map during play with .SwitchCurrentActionMap(String) and for some reason all my events are firing. Those of the actionmap I am changing from and the actionmap I am changing to. Is this expected behaviour ?
How Can I touch rotate camera system I cant find any usefull tutorial
are you making a local multiplayer game?
update to 1.4.4 in any case
No I am not. Just singleplayer touch screen controls. Was different schemes for different phases of game which would switch back an forth. I took control of it now with only 1 actionmap and handling events myself in script now. Seems to work.
Will check the version in any case , when I get back home.
Thank you
Has anyone used the "deviceId" variable from the InputDevice class?
i feel like it could be useful for me but idk how to grab it from the PlayerInput class
what are you trying to accomplish
It's a long story, but basically I want my game to detect what device/which player has clicked on a UI button and I was thinking about comparing the deviceId of the device that clicked on the button, to every player's deviceId stored in a list, and when it finds the matching ID, it will do certain actions to the specific player
or now that I think about it, maybe the PlayerIndex var is enough for it? edit: nvm, still dont think so
im really unsure, the documentation is extremely vague and I barely find anything on the web that is niche
wait
i think i figured something out
public void OnPlayerJoined(PlayerInput pi)
{
InputDevice ID = pi.devices[0];
int dID = ID.deviceId;
Debug.Log(dID);
}```
idk if this is a good way of doing it though, especially considering "devices" is an array
edit: seems like the array only has one element? lol ok
err it's not working as i expected, there must be a built in function for this
what u need help with?
@tardy lily
Basically i just want to detect what device was used to click on a UI object eg. Button
And then with that info find out what player uses the said device
It sounds like you want to detect which player has clicked on a UI button in your game. The PlayerInput class has a property called devices that contains a list of input devices (e.g. keyboard, mouse, gamepad, etc.) that are associated with a given player. The InputDevice class has a property called deviceId that uniquely identifies the device.
*One way to solve your problem would be to create a dictionary that maps device IDs to players, and then update the dictionary whenever a player joins or leaves the game. You can use the OnPlayerJoined and OnPlayerLeft methods to track when players join and leave the game, respectively.
Yes i've solved that issue already, tho i didnt use dictionaries
The problem is the step after that
Which is to actually detect which player clicked on a UI object
I thought OnClick would have a dynamic parameter for inputs or whatever but seems like it doesnt
Maybe eventsystems plays a role in this?
There's a multiplayer event system specifically for this
It's part of the input system package
Ah right, forgot about that lmao
I'm using new input system
I made a new action and binded it with "F" key
new I want when I press F a specific sprite to rotate
how someone help me with code plz
not sure why you were told to come here but anyway, reference the sprite public Transform mySprite; then you can do mySprite.Rotate(x,y,z); or
mySprite.rotation = Quaternion.Euler(x, y, z); or something else
Alexhalo3115 sent me here
you would be better off at code beginner, instead of this graveyard
yeah i saw, not sure the reason behind it though
I totally agree
ok I understand all that
but how to make the code happen only when I press F
do I put it under
{
if (value.isPressed )
{
Here?
}
note: action is binded with "F"
i mean try it
put a debug.log and see if it runs
ok
Anyone, How do I make my “getaAxis “ value so that instead of starting at (x,0,y) snapping back to 0 it would start at and snap back to my objects set position
I started learning unity like yesterday
dont crosspost and stay in #💻┃code-beginner
I wonder why this is a graveyard to begin with
I fear if ask anything about the input system then someone is gonna send me over here 😂
Hey! I'm looking for help.
I'm using Unity input manager and each time I Destroy player it gives me out of index errors from manager. How do I remove player correctly from Player Input manager?
Not the answer you are looking for, but imo it’s easier to just handle the player joining and assigning controllers yourself, than battle with player input manager
Does Control (Keyboard) not map to Command on macOS?
it does not.
mac keyboards also have Control keys
Problem is that a game I'm working on has a binding for Ctrl and scroll wheel
And it cannot be used on my Mac. Control and scroll wheel is the default binding for the Mac zoom accessibility feature and apps can't use that shortcut as a result.
Ctrl should not be treated as Control. It should be treated as Command
Bind it to command+scroll wheel on mac then and get rid of the ctrl+scroll with preprocessor?
There are lots of other bindings in the game that use Ctrl so I'm trying to think of the most streamlined way of having it use command on Mac
You can create or override this particular binding in code and use preprocessor directives to handle your case. ( # IF UNITY_MAC_OSX )
alternatively run a script in build phase which does search and replace in inputactions file
I don't think there is any "proper" way to remap a key, so all solutions are either manual work or a bit hacky
I would do a new control scheme to differentiate mac keyboard and then map all keyboard controls to both win and mac, besides those which use control/command
and then let preprocessor handle which control scheme is used
hey guys with the 'new' input system is there a way to have a button set as active? I am just testing it out but i cannot navigate through buttons with a joypad without first goign to click a button with the mouse
without setting it active via code
It's not a really an input system thing. Unity's UI navigation has always required that an object is "selected" first before you can start using UI navigation
the fix is to select an object initially
e.g. with EventSystem.current.SetSelectedGameObject(...)
ok thats cool just wnated to check there wasnt a setting already somewhere in the config
There is a setting, i believe on Canvas, like "initially selected object" or something, but in all my years of Unity I've never seen it working.
So either it's busted or I don't understand how to use it.
I can't seem to find the Command key in the dropdown that lets me select what input to use for a binding
I've tried searching both Command and cmd, neither of which bring up any results
Hey, is it only me or Event.current.delta won't output touchpad's X scroll?
The Y works fine, but X is always 0
Well, using the mouse Horizontal scroll it also always return 0, the Y works fine
I mean, it should work on Horizontal Wheel or?
Hey all. I have been trying to take the "Warriors" demo that was given with the New Input System and try to get it working with Mirror so that you can have Local and network play together (like Castle Crashers did). I have been struggling with this. Has anyone heard of anyone having done that before? Or is anyone able to help?
I've got a custom controller layout, but the raw HID data I need is in 2 bytes, as one short, and the byte order is backwards. How can I handle this as one variable with both parts in the right order?
for some reason this is only calling StartTouch once, and never EndTouch
it doesn't seem to cancel for some reason
controls.Player.TouchPress.canceled += ctx => EndTouch(ctx);
pass through actions never "cancel" afaik
oh also you're using Press and Release
meaning it will trigger performed on both press and release
Make it Action Type: Value Control Type: Vector2
And remove the press and release interaction
ah
the default interaction handles what you need.
I'm not sure it's going to really work with something like touch/position
maybe try binding it to Press [Touchscreen]
o that seems to work great, ty :)
though now it's blocking other input like interacting with game stuff lol
actually maybe not
how would i go about being able to hold over something to show a tooltip, but not interact with it unless it's just tapped?
You should use the event system for that kind of interaction
Either using the EventTrigger component, or a script with event system interfaces like IPointerEnterHandler/IPointerExitHandler
the stuff i want to interact with has all the pointer stuff
perfect, then use that
use pointer enter to show the tooltip, pointer exit to hide it
and Pointer Click to "interact" with it
gotcha i'll give that a shot
that works but it still interacts even if it's held, how would i cancel the click interaction when it's held?
if that makes sense
Are you using OnPointerDown or OnPointerClick
click
Ok so the click doesn't trigger until you click and release. So what you can do is start a timer in OnPointerDown (or record Time.time) then check how long it has been since that timer started in OnPointerClick
if it's been longer than some number you set (maybe 0.5 seconds?) don't do the interaction
Hey so im trying to reference a UI button in my scripts but when I use Input.GetButtonDown I get an error saying "Button is not set up" and telling me to go to Edit -> Settings -> Input. where do I go to set this up because I dont have settings or input under edit
GetButtonDown has nothing to do with UI buttons at all
it has to do with input devices like keyboards and gamepads
Ahhh that'll be my issue then
Hahhaa
Do you know off the top of your head how I do a similar thing with a UI button?
there is no similar thing
you hook up a listener to the on click event of the button to respond to the user clicking on it
you don't poll it in Update
Ahh Ok thanks for the help I thought there would be an easier way of doing this since I just want to change a variable
Can someone help me with the inputs here. For a project of mine, I have WASD set for movement in a Vector2 value, but I also need W and S for ladder climbing and I need it to trigger the climbing action when pressing the button for the first frame. Even though I made 2 actions, only the movement action works. Is there a way for the new Unity Input System, to assign 2 or more actions to the same buttons?
You don't need the press interaction
Also you don't really need two actions for this 🤔
unless you want them to be separately rebindable
Well I want the climbing actions to specifically be on a button press, whereas movement is a vector2
ok well - you don';t need the press interaction
how did you set it up in your code?
They should both work simultaneously
Before, I only used the vector 2 action but that would mean the button can just be held down instead of pressed to activate the climb action
Do they?
they should, hence why I asked to see how you set your code up
I tried debugging it and it wouldn't show anything
Sure just a sec
this is how it is currently set up
you don't have the appropriate method signature of OnClimbing
Also - you're usxing SendMessages mode
which doesn't really let you tell when a button is held vs pressed
I recommend switching to Unity Events mode
can you explain this one to me first?
ooooh send messages doesnt tell me when a button is pressed?
You are missing the InputValue parameter
nope - just the current value of the action
you'd have to do your own deduplication to detect a button press
does this mean I'd have to rework the movement since it uses the vector value
a very minor rework
I'm trying to capture steering wheel X value when window is out of focus. I have set runInBackground and IgnoreFocus in settings. Am I missing something for it to work? ♥️
I am just reading now that Device layout can override canRunInBackground but I am not sure if this will work and how do override wheel layout
From what I see Its not possible at all to do this. Im trying to figure out a way to do this with windows api. Any tips appreciated
so technically why is the xbox controller behave different than the playstation controller
the xbox controller gives a input only when you press something
the playstation controller is giving a input every single frame
define "giving input"?
if you plug in the xbox controller and give input unity says there is input now
if you plug in the playstation controller it gives me every frame input
What do you mean by "unity says there is input now"
what are you looking at
im looking at the input debugger
this screen
and every frame i get empty input?
but why
for what? A button? Joystick?
only when i give input on my controller it give a package with input
for everything
so i will give you a photo 1 sec
Some hardware devices may work differently - but after going through the input system's processing and disambiguation it shouldn't matter much right? The result is the same
well i don't use player input component
i use the
device change delegate
but when my game said ylou have a playstation controller
and i move with the mouse
he said computer but the next frame he say you have a controller
I think something is being lost in translation here...
this is my ps controller
this my xbox
so if i dont give input with my xbox there is no package
but with the ps controller i get every frame a package
ok but why is this an issue?
is this causing a problem in your game?
yep because when i detect gamepad input my mouse goes to the lock state in the middle and isnt visible then
when im detecting a mouse or the computer it goes out of the lockstate and is visible again
Is local multiplayer possible using the on-screen sticks/ on-screen buttons?
We're making a project for a proprietary touch-screen table that allows up to 20 touch controls.
We'd like to split the screen into segments for the different players and have them all use separate on-screen sticks & buttons.
The OnScreenControls only have a controlPath variable, but as far as I'm aware there is no option to select which device it's simulating it on.
Unfortunately I can't just take the code from OnScreenControl and use it in my own, it uses a lot of code that's internal so it's as far as I'm aware completely impossible to make your own variant of these inputs.
Is it safe to change the script created by new Input System? Won't the changes be discarded? I want to create an interface to use in my classes so that they do not directly depend on the class
Not really a good idea, it will get wiped out any time you make a change.
Do note that the generated code produces a partial class
So you can simply add your own supplemental .cs file adding more stuff to the partial class
I came up with idea of getting InputAction as dependency
And I first create the map, then get actions from it and then can inject them wherever I want
I don't really see why you would need to modify the generated code file to do that
It's a new idea not related to my last question
Does anyone know how to convert the fps microgame to use the new input system
Is there a way to check what binding is currently in use for the same action
like if you had to different bindings for the same action
i find a way to work with this
@austere grotto how much of a difference is there between using generated script and the player input component? i started with generated and was wondering if there's any good reason to switch
PlayerInput is most useful if you're making a local multiplayer game
anything besides that?
Also lets you subscribe your callbacks in the inspector
Or use the send messages mode. Both of which are lower code
Quick question, I imagine (I hope) there's a simple solution to this— I have a control scheme that I've made (keyboard) just for testing, but I want to disable it when building the game. Is there any way to do that without deleting the entire action map, because I use those bindings in development
all of those properties with none require input
IDk what this is and what a "pos" means
Just delete your input module and recreate it. There's defaults that are fine
now it works, but I have this mysterious bug, that always moves my sliders to the right corner. it only stops if it reached the right corner or if I press the arrowkeys.
are you using the default ui action asset or your own
now the default ui action, I checked it and it was not even existing before @austere grotto told me to remove and add the module
did you disable your gameplay ui action asset when you paused the game
now it works, but I always have this bug that my sliders go to the right side. I only can avoid it, if I press something on the arrow key or if I click in the background around the sliders.
disable what?
the only things I change, after the option panel was enabled is:
MovementAllowedPlaceholder.MovementAllowed = false;
Cursor.lockState = CursorLockMode.Confined;
Cursor.visible = true;
Time.timeScale = 0f;
comment out Cursor.lockState = CursorLockMode.Confined; and try again
In this case, nothing is moving, but I also cant click anything or my mouse gets invisible.
idk then
you'll have to isolate the issue by disabling scripts and finding out which one is affecting it
I tried to google it and I found a dude that have the exact same issue and no answers since 2013:
https://forum.unity.com/threads/slider-keeps-sliding-until-the-player-clicks-again.854419/
google isn't going to give you the answer to everything
sometimes you need to figure it out yourself
I saw that issue also in some other projects and I think it have soemthing to do with the basics how the UI in unity works, but dont know how to fix that.
I know that I never wrote a script that is for moving the sliders automaticly in the options.
tell me how? what do I even have to search for?
It stops, if I click in the panel around the sliders.
i would start by making an empty scene with only the ui active
to see if the sliders still have the issues with no other scripts in the scene
then I would add more scripts to see which one is causing the issue
my sliders work fine with the new input system and default ui input actions
the thing is, it only happens once after starting the game, I have to press the arrow keys to complettly stop the moving and clicking in the background does it only pause, until I try to click a slider again.
if I close the menu and open it again, it doesent move anymore, only after starting the game.
even if I change the scene while the games runs, the bug no longer happens, only if I truely start the game fresh in the unity editor playmode or if I run the exported .exe build.
Then theres a script causing the error
I think the problem is bigger in the unity play mode than in the actual build. because you have to pass the mainmenu first and not the actual game scene and after you canged the scene from the mainmenu to the game, the bug is not happening. its only happening, if I start the actual game scene directly and the bug is happening only that long, until I pressed a arrowkey.
thats so weird. if I would have a script that would mess this up, why would this script not mess it up if I start the game in the mainmenu and change it to the gamescnene?
Hey, how do I access the mouse's scroll wheel inputs? Can't find it in the bindings of the new input system
Make sure your action type is Value / Axis
Guess I don't have the same version as you, when doing this I only get scoll X and scroll Y.
show how you configured the action itself
anyway isn't scroll y what you want though?
Yes but I'd rather have it behave as a button, idk what's the float I'll get from reading that value
you will get a positive value when scrolling up and negative when scrolling down
Just hook it up and print the value and play with it to understand how it works
then use it
I'll have to check it, thanks
I couldn't figure out how to get the scroll to begin with so that's enough to get me started 🙂
Hey devs
I am having this weird behavior in InputSystem
Feels like Gamepad.current get cached when you connect your controller and when you disconnect it and try to run the game again, the current would still say as if it is connected to the device
What I did is create InputActions, add the maps and in code I would create an instance for these actions.
Is this issue common or did I do something wrong?
You can check the code here if needed:
https://hatebin.com/hgeytmfzvo
how do I use xr input from 2018.3 in code
with the new input system, when you press a key it runs the associated event twice, causing my player to move 2 squares, is there anyway to make it only send one event?
ok figured it out, turns out all you have to do is a nice little if statement to check for context.started and then just dont do any of the movement stuff if it is true
how do you do a press and hold with the new input system, ive literally spent 3 hours and i cannot understand it, do you have to do it with flags etc? seems a bit low level and ridiculous
Depends what you mean by "press and hold"
Do you want to run something every frame while it's held?
Or do you want to do something (once) after holding for a certain amount of time?
actually is there a 3rd way than the one i mentioned?
if we can make a button keep sending a performed event while its pressed down then we could perform a function while its held
I just dont know how to do that
Ignore this, found what I needed.
If you send Unity Events in your code you can use the callback context and do context.performed (interactions set up in your .inputactions).
If you want to do something as long as its held, you actually just wouldn't do if (context.performed). By default it will run your event every time a change in the input is detected. So it will set it to a value when its changed and when its not changed it won't do anything so you can keep a variable that has the up to date status.
Then you just run your code on tick if the variable is what you want it to be. Code in the event should be kept really basic and not intended to use as a tick. Otherwise you'll create another game loop and things won't always line up expectedly.
The only way to do this would be to write a custom interaction
I think it would be a mistake though. If you want to use event-based input, it's silly to make it fire an event every frame or something like that. That's not an event. Events should be when things change. Not "things are still the same this frame". If you want to do something every frame that's what Update is for.
True
I still haven't found an answer for that, so bump
thanks guys got it working, still getting used to new input system 🙂
though now im trying to implement it on a new game and cant get the calls going lol
how do you make it pass in a callback instead of an inputvalue?
If you use SendMessages mode, you only get InputValue
ohh cheers
Hello guys, i'm new here and i did search some of the chats here already, but i didn't quite find what i am looking for yet. So please bear with me and have mercy..
I am trying to implement a feature like in the following video, but with a Windows MR Headset via OpenXR.
https://www.youtube.com/watch?v=WCTFwliXJmA
How do i figure out how to get the right input actions to implement the jetpack movement? Has someone done something like that before and is willing to help? I would appreciate any tips and hints for this. 🙂
Learn how to make a jet pack game in Unity for the Quest 2. I show you everything step by step, from the oculus integration to fine tuning the physics. Zip around the canyon, fly through caves and try not to smack into the rocks.
0:00 Intro
0:46 Oculus integration
3:05 Understand oculus scripts
7:50 Create player with jetpack
11:55 Jetpack in...
Hello, is there a way to have deadzones set up in input action maps/ make them read less input?
using the updated input system applied to UI (as it is by default), how do I get something to happen when an inputfield is submitted? Nothing in the documentation is helping whatsoever
The same way you always have. Nothing has changed about UI stuff except the type of input module you need on the event system. Everything else is the same
Hello is the way on mobile to check if I get touch and it isnt on Canvas button or etc?
I mean, I have this code to do something when screen touched but it also active when I click a button. Is the way to avoid this?
if(Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Began)
{
//Do something
}
}
EventSystem's IsPointerOverGameObject probably works
(Unity 2021.3.11f1) Index and movement issue.
Hello OUD! Hope this is the right place to ask a question. ^^
Sorry in advance for my broken english.
I'm currently working on a VR Unity project in the above mentioned LTS version.
Currently i'm trying to get my "PlayerCameraRig" to have continues movement when using the index controllers, but i don't seam to be able to get it to work. I have tried the following and a few other things:
-Following online tutorials on costume scripts for index controllers (with no luck)
-"Converting" a standart PC keyboard script to use Index inputs.
-Using the default XRinteraction kit to try and build a input system.
-Adding alot of random compontents like snap-turn and teleport to try and get any movement.
-Editing prefab scripts that should work for other controllers (Vive and Occulus).
It also terrifies me that when i read online they say that the 2020 version is "allegedly unsupported" by current SteamVR and OpenVR.
Thanks for taking the time to read this and i hope my explanation is adequate. ^v^
Otherwise feel free to ask away for any info needed!
PS: i should mention that the index models that are in the current project dose track and move the thumb-stick when i do it irl, so i would assume that it dose have SOME input.
anyone else having serious gamepad issues in the new 2022.2 release?
my gamepad is going crazy, Nintendo Switch Pro controller
random callback action events are called and button presses are seen as cancelled after one frame
is it normal when you connect your ps4 gamepad to unity, the light of it is not shining and the gamepad won't react to for example pressing a button?
nevermind I connected it via cable instead of bluetooth
If I have a controller scheme that only gets Pad and Joystick inputs are keyboard presses should get ignore right? Because I have the default scheme on the Pad only scheme and I still get the events activated when doing the keyboard presses. Is it because im Invoking C# Events?
player input looks like this:
scheme:
GamePad is Required
Control scheme is not going to be respected unless you're actually using the PlayerInput component for listening to events etc
which you are not
I see
btw "invoke C# events" is widely misunderstood and it's very unlikely you're using it as intended
thanks a lot
What is "Gravity" in the Input Manager options?
Thanks! Also appreciate the link, that will definitely help for future things.
how to call a function when an InputAction is performed, but not started or cancelled?
please?
Is it something like this?
if (!ctx.canceled && !ctx.started)
{
_started = true;
_updatesController.AddUpdateCallback(OnUpdate);
_updatesController.AddFixedUpdateCallback(OnFixedUpdate);
}```
if(ctx.performed)
I thought canceled and started are considered performed too. So that if you make a single press while subscribed to .performed you will get your method called thrice
No they're all separate
print (ctx.phase)
I believe I started with a video where the author pressed spacebar once and got .performed executed thrice
Maybe even CodeMonkey?
Pay careful attention to what their code actually did
Yeah just tested and indeed you are right
Also note that performed will happen every time the control changes to another non zero actuation. So for example many times for a joystick, any time it changes at all
For a keyboard key it will just be once
And yeah it depends on the interaction too
I hoped I could listen to an event and the event would be called each frame or something like this
So I have OnGroundState and InAirState. Once my character leaves ground, my move functionality gets disabled. Once the character gets grounded again, movement script gets enabled again and subscribes to .started to start moving. But the thing is that if I didn't cancel movementAction during the character's absense on ground, once it gets grounded I will have to cancel the action and start it again. Unpress the button and press it again in other words. I instead want the character to continue moving without me unpressing the button
I am thinking of checking on whether the InputAction is active once my movement gets activated
What do you think about it? Perhaps you can offer a better solution?
I wouldn't overcomplicate it:
void Update() {
if (grounded) {
Move();
}
}```
small question, can i use both the old and the new input system at the same time?
Yes but you'll take a performance hit
ahh okay, thanks
was wondering why my old input stuff still works
Project Settings -> Player -> Active Input Handling determines which to use (or both)
Why is the InputAction.CallbackContext a struct??? Why not a class??
For performance reasons presumably - so as not to allocate a bunch of garbage.
I thought it would be even worse for performance? Because the values would be copied each time the struct is passed somewhere
not a big deal
also how much passing around of the whole CallBackContext are you doing anyway
Am using decorators
You can also pass it by reference using in or ref
So indefinite
not really sure what this means tbh
pattern when instead of inheriting from something you implement the same interface as it does and get it into you to call its functions with your additional functionality
public class StateDecorator : IState
{
public StateDecorator(IState state)
{
_state = state;
}
private readonly IState _state;
public void IStateFunction()
{
_state.IStateFunction();
//additional functionality
}
}```
You're doing this with CallbackContext?
Seems kinda heavyweight
what kind of decorator(s) are you wanting to use
Gonna have something like
public void Activate(CallbackContext ctx)
{
_.Activate(ctx);
//
}```
All kinds of? But I think no more than a few in a row
What are the use cases?
A security check for input events?
No, for some other game stuff, kinda, do you have enough mana?
So I was thinking perhaps using a class would be more beneficial
What do you think?
I think you're trying to couple your input handling code a bit too tightly to your game logic code.
how so
CallbackContext is an object containing information about an input event. Just let it be an input event
If you want to decorate something, decorate your "CastSpell" function to have the "do you have enough mana" check
Frankly speaking, I originally asked in this channel in hopes to get an insight on "why exactly is InputAction.CallbackContext a struct instead of a class" not because I am making decorators for something directly related to input, but because I am making another feature based on callbacks and was concerned about performance
I thought it would be best to ask here
Right and I answered that. It's for performance / GC allocation reasons I would imagine
There's also nothing that can be done about it
ive been trying to setup local multiplayer using the PlayerInputManager, but for some reason when i have a keyboard player and 1 or more controller players, the controllers also affect the keyboard player (but not the other controllers).
the Move input action is synced with the keyboard player (although i fixed this randomly by playing with the input actions, then broke it again), and most notably, the controllers east button makes the keyboard player jump even though the east button isnt assigned at all... this only happens when the keyboard player has Space as their jump button!
im not sure what the issue is, but im wondering if i can LOCK a controller to each player somehow? or maybe theres another solution im missing
The player disambiguation is usually done through control schemes
it should automatically assign device / sets of devices that match control schemes to players
You might be processing input in a weird way to cause this issue
hm, ive setup both a keyboard and controller control scheme. i wonder how i could be processing input in a weird way, im using the PlayerInput component to send messages to the gameobject.
This sounds correct... what are you doing with the input once you receive it?
Maybe share your code
{
if (movementLimiter.instance.CharacterCanMove)
directionX = context.Get<Vector2>().x;
}
The OnMove input action is a Vector2 Value
is that enough to show? dont wanna send the whole script unless i have to, just because itd be a waste of your time
well what happens with directionX?
And how is directionX declared?
total newb question here. you know how you setup OnEnable and OnDisable events for the new input system actions? What do these really do and how would you go about using them. I have a UI I'm implementing for my project and when certain parts of the UI are open I want to make sure that the input system controls the UI instead of the in-game objects, so I need to disable certain controls. I of course could just setup some sort of system with bools in a script to control this but I feel like this is functionality the new input system already should be able to handle given the OnEnable and OnDisable functions?
or do those functions simply run automatically when the gameobject the control actions are attached to is itself enabled / disabled?
public float directionX;
private void Update() {
//Used to stop movement when the character is playing her death animation
if (!movementLimiter.instance.CharacterCanMove) {
directionX = 0;
}
//Used to flip the character's sprite when she changes direction
//Also tells us that we are currently pressing a direction button
if (directionX != 0) {
transform.localScale = new Vector3(directionX > 0 ? 1 : -1, 1, 1);
pressingKey = true;
}
else {
pressingKey = false;
}
//Calculate's the character's desired velocity - which is the direction you are facing, multiplied by the character's maximum speed
//Friction is not used in this game
desiredVelocity = new Vector2(directionX, 0f) * Mathf.Max(maxSpeed - friction, 0f);
}
private void runWithoutAcceleration() // ran in fixed update
{
//If we're not using acceleration and deceleration, just send our desired velocity (direction * max speed) to the Rigidbody
velocity.x = desiredVelocity.x;
body.velocity = velocity;
}
OnEnable and OnDisable have nothing to do with the input system. Those are part of MonoBehaviour and just run when your script is enabled and disabled.
As for your overall question about UI, are you asking how to make for example mouse stuff not affect the game world when your moouse is over a UI element?
Good to know, thank you for clarifying. The idea here is I have an area of my screen dedicated to a UI that shows hotkeys for showing certain UI windows I'm making (with the ui-toolkit, not the default ui stuff)
and when a hotkey is pressed to enable a ui window the idea is to halt certain keys such as the wasd and arrow keys from controlling an in-game cursor object
so that they can instead be used to select buttons within the ui window
You can do this by enabling / disabling action maps
Make a separate action map for controller the in game character, and a separate one for the UI
disable/enable them as needed
so lets say i have a 2d vector input action for controlling the in game object. I can just do something like action.disable() in the script where that action is controlled?
Ah I get it
thank you for the help
you would do e.g. ActionMap playerActions _playerInput.actions.GetActionMap("PlayerActions");
THen you can disable the entire action map like playerActions.Disable();
rather than individual InputActions
hi im new to input actions im not sure how to read the input of a joystick and reference that in c#? i want to get the horizontal axis input
theres a few different ways, but the simplest, if you want a replacement for KeyCode, you can make a InputAction variable. you would have to enable it and subscribe a method to it using something like:
public InputAction moveAction;
moveAction.Enable();
moveAction.performed += context => MoveAction(context);
in the editdor you would add the controllers joystick btw
then your method would look like:
private void MoveAction(InputAction.CallbackContext context)
{
var movement = context.ReadValue<float>();
}
if i remember right anyways
was looking for a link to the amazing unity docs, they explain it well. anyways i found on the quickstart page an easier way: Vector2 move = gamepad.leftStick.ReadValue();
check it out https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/QuickStartGuide.html
yeah thanks but now nothing is responding lol im so fucked
surely these are correct?
i think the vector2 is fine
im not sure about passing in bool
im not sure what a button returns tbh
i wish unity would put the documentation on the main site
unity and documentation don't belong in the same sentence
well i can tell you the way i do things with a short example.
make sure your game object has the player input component on it with the input action asset assigned to it, and set to "send messages"
make a variable for your input action asset and however many variables you need for your actions
private PlayerInput _PlayerInput;
private InputAction moveAction;
add these
private void OnEnable()
{
moveAction.Enable();
}
private void OnDisable()
{
moveAction.Disable();
}
in your awake or start function do
_PlayerInput = GetComponent<PlayerInput>();
moveAction = _PlayerInput.actions["Move"];
from here you can get input from it in several ways. if you want continuous input in your update function you can do this
moveDirection = Vector2Int.RoundToInt(moveAction.ReadValue<Vector2>());
if you want to run a function once on button press, or once on button unpress (cancel) you can do this (note: this is a different input action because the moveAction input action in my script doesn't have these)
_InputAction_FreeRotate.started += ctx => FreeRotateCameraStarted(ctx);
_InputAction_FreeRotate.canceled += ctx => FreeRotateCameraCanceled(ctx);
and then you create the functions like this
void FreeRotateCameraStarted(InputAction.CallbackContext ctx)
{
...
}
void FreeRotateCameraCanceled(InputAction.CallbackContext ctx)
{
...
}
here is the majority of a script I used with some unimportant bits cut out
I've seen scripts that will try to read the value of the action. from what i understand you should pass in a vector2 for a movement action but im notsure what to pass in for a button
a boolean?
ie. movement.ReadValue<Type>();
I actually don't know myself. I just do _InputAction_Zoom.started += ctx => ZoomCameraStarted(ctx);
this still fires on button press ¯_(ツ)_/¯
Jump.IsPressed() or WasPressedThisFrame()
Is there a way of using control schemes when Invoking C# events?
Yes control schemes work with "invoke C# events" but I can almost guarantee you are not using "invoke C# events" properly
Invoke C# events basically refers to this event in particular:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/api/UnityEngine.InputSystem.PlayerInput.html#UnityEngine_InputSystem_PlayerInput_onActionTriggered
If you're listening to that event, it should work.
thanks, big help
hey how would i perform a function if two conditions are met?
i have a function for an up attack
and want to only perform it if the hold the joystick up and also press the attack button
im not sure through syntax how to express this though
you wouldn't put that logic in the input context callback
You can make a Button with a Single Modifier input action
then all that will be encapsulated in a single input action
ah thanks that worked but now other things seem to be affected. firstly, in my functions i already had a couroutine to make a cooldown but this seems to be ignored by the input. secondly, i should only do a down attack if im off the ground and i added an if statement with the input nested inside it but this doesn't work
is it becuase it is in the awake function?
the ifs should be in the attack code
ah okay ill try that
so far everything is owrking now except for the pause button and im not sure why as the implementation should just be the same
im not sure what's wrong here
Im making a turn based game with multiple mobs and an inventory system that i need to navigate from each one with a joystick controller and a mouse. Do I need to use buttons for this?
I've been learning Unity a few weeks, and I've tried to move my movement to the new input system, but if I do it breaks my buffered jumps
void Jump() {
isGrounded = boxcollider2d.IsTouchingLayers(LayerMask.GetMask("Ground"));
if(isGrounded){
coyoteTimer = coyoteTime;
}
else {
coyoteTimer -= Time.deltaTime;
}
if (Input.GetButtonDown("Jump")){
jumpBufferTimer = jumpBufferTime;
}
else{
jumpBufferTimer -= Time.deltaTime;
}
if (jumpBufferTimer >= 0f && coyoteTimer > 0f){
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpHeight);
jumpBufferTimer = 0f;
}
if(Input.GetButtonUp("Jump") && rb2d.velocity.y > 0f)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, rb2d.velocity.y * 0.5f);
coyoteTimer = 0;
}
}
This works absolutely fine
public void Jump(InputAction.CallbackContext context) {
isGrounded = boxcollider2d.IsTouchingLayers(LayerMask.GetMask("Ground"));
if(isGrounded){
coyoteTimer = coyoteTime;
}
else {
coyoteTimer -= Time.deltaTime;
}
if (context.performed){
jumpBufferTimer = jumpBufferTime;
}
else{
jumpBufferTimer -= Time.deltaTime;
}
if (jumpBufferTimer >= 0f && coyoteTimer > 0f){
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpHeight);
jumpBufferTimer = 0f;
}
if(context.canceled && rb2d.velocity.y > 0f)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, rb2d.velocity.y * 0.5f);
coyoteTimer = 0;
}
}``` but this makes the code unpredictable and breaks it
maybe write isPaused = !isPaused; before ur if statement
It seems replacing Input.GetKeyDown with context.performed isn't reliable?
Same thing. The code is still broken
coyoteTimer = coyoteTime;
}
else {
coyoteTimer -= Time.deltaTime;
}```
this code needs to be moved elsewhere
what u need to understand abt the new input system is it only runs code when buttons are pressed and released
basically you gotta refactor almost everything
if you had everything in update
Ah gotcha
I did that and it fixed some unusual behaviour, but the buffer still doesn't activate
hi ps4 controller cant be recognized by unity
where is the best way to recognize ps4 controller on windows
by input system
google unity ps4 controller not recognised
Hi, need some help as for some reason my DownAttack isn't triggering. For some context, my attacks works as follows
if canAttack - do straight attack
if canAttackUp - do up attack
if canAttackDown and !grounded - do down attack
Whilst this worked fine with the old input system, for some reason only my downAttack isn't working. I've already checked and my Animator controller is fine and nothing is wrong with that so I am unsure why not. For the controller I have the DownAttack action to be a button with a joystick modifier. Here is the relevant sections of code
public void StraightAttack()
{
if (canAttack)
{
canAttack = false; //since in attack phase, they can't attack until it is done. therefore, set to false
animator.SetBool("IsAttacking", true); //start attack animation
StartCoroutine(AttackCooldown());
}
}
public void DownAttack()
{
if(canAttackDown && !cc2d.grounded)
{
canAttackDown = false;
animator.SetBool("IsAttackingDown", true);
StartCoroutine(AttackCooldown());
}
}
private void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
controls = new InputMaster();
controls.Player.Attack.performed += ctx => StraightAttack();
controls.Player.UpAttack.performed += ctx => UpAttack();
controls.Player.DownAttack.performed += ctx => DownAttack();
controls.Player.ProjectileAttack.performed += ctx => ProjectileAttack();
}
You never did controls.Enable();
well ya didn't share it with us!
soz
my other buttons do work though i did mention
my up attack is fine and and so is the regular attack
Put Debug.Log() inside the functions (outside the if statements) to make sure the code is running
If they are then it's just a logic problem with your code
huh, i put the debug log statement and the function does seem to run
yet im confused as to why it is instead animating a regular attack instead of a downwards attack
I've set the bool for IsAttackingDown so I'd assume it'd set that
I thought maybe it's something to do with my input modifiers but if up attack works fine with a modifier I don't see why down attack shouldn't when it's been implemented the same
and furthermore, when trying to do it using keyboard inputs that use the old input system, it doesn't even debug that it is working
even though Ive set the editor settings to take in both types of input
I have a feeling it may be to do with the animator as it doesn't even register that AttackingDown is set to true
perhaps it is somehow due to the input controls?
I think it's almost definitely nothing to do with input
since you checked and it's printing properly when input happens
It's just your code logic and/or how you set up your animator etc
yeah most likely ill spend some time tinkering
Hi, how do I prevent Axis Snapping when using the keyboard with the new input system? With legacy, it was a checkbox you tick, but I couldn't find it in the new one
Hi. How to set joystick 4 direction movement topdown 2D ?
Trying to adapt a combo system to the new system. I'm getting stuck as the old system was very easy to do a foreach(list of keys) getkey(key from list), check scriptible object combo, call timer. Call combo as filled.
Now I'm getting "getaction not found" etc. There has to be a github somewhere with 4 deep combos that doesn't need a behavior tree or an FSM. There's not that many combos, but they are often move, then button button kinda things.
I recommend watching a tutorial on the New Input system, you would use callback contexts to check for key presses, then I usually just toggle a bool as a result, then the game will react according to which of those bools is true.
As far as im aware it would be very difficult to do a foreach on all your pressed keys unless you do it based on said bools or something
You can do the same foreach on your InputActions, just throw them in a list
I do think a state machine really is kind of a must for a combo system though
Is there a way I can have the Input Actions editor show all devices for binding? (I'm on a windows development machine targeting mobile devices and need an accelerometer sensor. I can see and add it in the input system settings, but I can't ever see it to bind to.)
Oh, I see. Apparently the input system absolutely will not take an accelerometer input as a Vector2, it must be a Vector3.
I have imported a script that uses the old input system however i am using the new one and im getting the error "You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Setting" this is the code i need to change, any help would be great 🙂
and these are my input actions
I'm having some unanticipated behaviour with Input System and C# Events.
I have an Action Map for the player, and an Action Map for UI.
The player can press 'E' to Interact with something, and the UI manager will show a panel, and instantiate some choice buttons.
When the UI manager shows the panel, it switches from the 'player' action map, to the 'UI' action map.
When the panel instantiates it's choice buttons, it has the first button be 'SetSelecteGameObject' for the event system.
The player can then press 'E' to submit/Accept on the selected button (or navigate to other choices)
What actually happens is:
- E is pressed
- A successfull interaction is triggered
- the panel is opened
- the buttons are instantiated
- the first button is SetSelectedGameObject
- Action map is changed to UI
- ... the button registers an onClick event (???)
- the panel closes
- Action map is changed to player
- A successfull interaction is triggered (again)
- the panel is opened (again)
- the buttons are instantiated (yep)
- the first button is SetSelectedGameObject (here we go)
- Action map is changed to UI
- the button registers an onClick event (again, no button press)
- the panel closes...
are you using bools with your input system
like when you perform an input action you set a value to true and other methods check for that bool
So this is a somewhat common problem and I know there's a good workaround for it just gotta dig it up...
Ah you mean like "canJump" or something? no. I just have
inputActionsAsset.CapsulePlayerControls.Interact.performed += ctx => InteractAction(); on my player controller,
and I let the Event System InputSystemUIModule component handle UI input
So my thinking is that the Action is being recieved by both, and that the UIModule is like... waiting for a chance to use it, or responding late or something
(It's not InitialStateCheck by the way, although that produces even longer loops 😅 in a similar way)
yah dont use the same method on both
same method? I figured InputSystemUI module only cares about the UI action mappings I assigned to it
I know for sure one way to do this is to just use a coroutine and wait a single frame before enabling the other action map
I have a gut feeling this is the case, specifically between InputActions.Disable, SetSelectedGameObject, and InputMap.Enable
just really let everything settle in 😛
yep basically I think something like this would be appropriate:
gameActionMap.Disable();
// activate the UI
ui.SetActive(true);
EventSystem.current.SetSelectedGameObject(whatever):
// wait one frame
yield return null;
uiActionMap.Enable();```
I was like 50% sure there's some other way to do it but I know this workaround will work
thanks, I think I avoided this so far because things are a bit of a mess and this is happening across 4 scripts 😛 but my ui will need some time for animation/tweens anyway so it will be good functionality to add!
no joy, and a new twist.
gameActionMap.Disable();
// activate the UI
ui.SetActive(true);
EventSystem.current.SetSelectedGameObject(whatever):
// wait one frame
yield return null;
//uiActionMap.Enable(); comment this out, let's NOT enable the UI Action map...
same bug! 😄 Even with all actions disabled, SetSelectedGameObject triggers the button
The InputSystemUIModule is still allowing input though! so I guess my actions aren't as "disabled" as I thought.
this is looking pretty suspicious:
basically if some event(?) hasn't been used, and the Event System has a selected game object,
then check if we have a valid submit action, and if that action was pressed this frame.
if so, then execute events on the current selected object!
The problem is that, we changed action maps before selecting a game object. And we disabled all input mappings!
but even with input mappings disabled, InputSystemUIModule still handles them on it's own anyway. If I disable it, the problem goes away! (but now I have no UI input)
it doesn't matter if I try to wait till the next frame, because InputSystemUIModule will execute it before I can even yield.. somehow??
change it so current selected object is assigned next frame then
How do I get the new input system to continuously read from a held-down key instead of reading it only upon pressing?
Here's the code I used:
public FR_Inputs controls;
private void Awake()
{
cc = GetComponent<CapsuleCollider>();
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
defaultHeight = cc.height;
defaultMoveSpeed = moveSpeed;
controls = new FR_Inputs();
controls.Player.Move.performed += ctx => MovePlayer(ctx.ReadValue<Vector2>());
}
private void OnEnable()
{
controls.Enable();
}
private void OnDisable()
{
controls.Disable();
}
private void MovePlayer(Vector2 dir)
{
//Calculate movement direction
if (!freezeMovement)
{
moveDir = orientation.forward * dir.y + orientation.right * dir.x;
rb.AddForce(moveDir.normalized * moveSpeed * 10f * (isGrounded ? 1f : airMultiplier), ForceMode.Force);
}
}
Doesn't work. I even wait for a few seconds, SetSelected always fires the onclick event of the selected button. I'm seriously expecting this to be a bug
You can use Update to run code every frame
and poll the input action there
I got that.
Oh?
I guess my problem was that I tried doing it in FixedUpdate...
Vector2 input = controls.Player.Move.ReadValue<Vector2>();
'Cuz that's what worked before, with the old system.
Let's see what happens if I do it in Update...
If you're adding forces it should be in FixedUpdate
It's fine to read a continuous input like a joystick in FixedUpdate
You realize I'm telling you to get red of the event handling stuff right?
... no?
That was my point
You mean this line?
controls.Player.Move.performed += ctx => MovePlayer(ctx.ReadValue<Vector2>());
Yeah I figured doing it your way would mean getting rid of that line.
The simple approach:
Vector2 moveInput;
void Update() {
moveInput = controls.Player.Move.ReadValue<Vector2>();
}
void FixedUpdate() {
// movement code using `moveInput` here
}```
AYY IT WORKS. 😄
Oh wow... that's some snappy movement... 🤔
Alright, let's see what happens if I poll it under FixedInput now... 🤔
well...
- You're normalizing the joystick input so you can't regulate the speed by partially tilting the stick
- You're multiplying the force by 10 inexplicably
I see now... putting that poll under FixedUpdate emulates the movement scheme I had from before. 😄
So I'll keep it there.
Thanks so much! 😄
@austere grotto Oi, I'm gonna need more help now... 🤔
So that control scheme was all well and good for reading a Vector2, but what about for button controls? Would I read a bool from that?
for a button, using the event-based approach is quite good
but you could also just read it from Update if you want
using myInputAction.WasPressedThisFrame();
basically WasPressedThisFrame() is like GetButtonDown and IsPressed() is like GetButton
Ah, so then I should go for IsPressed then.
if you want to see if it's held currently, yes
Exactly.