#🖱️┃input-system
1 messages · Page 11 of 1
So I am trying to implement the new Input system into my game. So far I really enjoy working with it, however, some things are confusing me here.
When setting it up in a new script I am making a new CustomInputAction (baked C# script) and referencing that to get the controls and the callback.
But i realized something. If now I want to change the Action Maps, do I now have to do that for every single script that makes a new CustomInputAction to reference? So instead I should maybe have some singleton script make the new CustomInputAction, and then all other scripts can reference it from there?
What would you guys recommend? ^^
I think there's a lot of benefits to centrally managing a single instance of your input asset (and generated C# class).
The main benefit would be that you can enable/disable action maps and that will be effective globally.
A side benefit would be that there's only one file to change when you change your action asset
Alright, I will do that then. Thank you! ^^
For some reason my tab key isn't working but my controller's select button does?
{
Debug.Log("Pressed");
if (isPaused)
{
Resume();
}
else
{
Pause();
}
}```
this input is mapped to Tab and the select button
even when I map it to a different key it still wont work
so what the hell is going on?
the other keys work except for the key thats bound to the map button for some reason?
keep in mind that the controller button works, so the command clearly works
so why doesnt the damn tab key work?
nvm got it to work
the issue was that the player object had the player input component and I guess more than one object with that component causes issues
oh yeah
i believe that having two player input components means that you want to have two players
I wasn't planning on that, considering the type of game i was working on
Basically the map screen object also had the player input component
that sounds very similar to something I did once, lol
I had a player input component on the player's map and on the player
and it broke -- this was during a game jam, so i didn't really take any time to analyze it
in that case, I just gave the player a reference to the map and passed the inputs along
Hi guys. I'm trying to create a controller using the new input system, but got stuck when I added rotation. I think its because my OnMovementPerformed function checks only the last input, and doesn't read them simultaneously.
{
movementInput = value.ReadValue<Vector2>();
}```
Is the best way to add to the values and check them by checking if each keyboard key is pressed like below? Or is there a neater / one line version I can do like above?
{
horizontalMovement -= 1f;
}
if (Keyboard.current.dKey.isPressed)
{
horizontalMovement += 1f;
}```
show me how you configured the action
First I subscribed to it
{
playerInput.Enable();
//playerInput.Gameplay.Move.performed += OnMovementPerformed;
//playerInput.Gameplay.Move.canceled += OnMovementCancelled;
}```
as in, in the input action asset
where you told the input system what keys to use and what the name of the action is
I just followed a tutorial online and it was using an inputaction "movementInput" and then assigning it based on the readVlaue of the callback context
But that wouldn't let me rotate, so I've commented out all of that and now I'm just checking if keys pressed
It works as I intended, but now Im wondering what about if someone uses a joystick? Surely theres a better way than just checking buttons pressed?
There's nothing on the inspector apart from my movespeed and rotation speed variables
heres my full code though
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
where did you define the input action
you're using PlayerInput
so you must have given it an Input Action Asset
e.g.
So I've just assigned it in awake:
playerInput = new PlayerInput();
i am also confused by these lines
playerInput.Gameplay.Move.performed
this looks more like what you'd do if you were using an input action asset with "Generate C# Class" enabled
which lets you reference the action maps and actions by name in code
PlayerInput does not do that.
those cause compiler errors when uncommented, yes?
i would also expect this to not work, since you can't just construct a component: you need to go through GameObject.AddComponent for that.
Well they do now yes but I was using that way before, but like I say when I did it that way, the .isPerformed is only checking the last value so if I press two buttons at the same time it didn't recognise that and thats why I cant rotate. So I've commented that out and I'm just using keys
that way never should have worked, so you must have been doing something differently before
if you want a Vector2 input based on the WASD keys, then you need to:
- create an action
- give that action a composite up/down/left/right binding
- assign the keys to the binding
this is a screenshot from an Input Action Asset
I've done that already
okay, so you do have an asset
can you show me a screenshot of it?
i want to make sure we're on the same page
So previously I was reading the Vector2 from the PlayerInput and changing the movementInput value based on this, then moving my character based on that movementInput float value
okay, so that looks good
now, you need to add a Player Input component to the game object, rather than trying to construct one in Awake
and you need to assign that input action asset to it
e.g.
this will, by itself, make sure that the action map gets enabled.
you can also tell the Player Input component to call methods when actions are performed/canceled/etc.
for example:
If you want to directly register for the performed callback, like you were doing here
then you should add an InputActionReference field to the class
it'll look a little like this
you can reference any action from an action asset
then, you can go ahead and do, say:
moveAction.action.performed += (context) => Debug.Log("The move action was performed");
Although, for actions that represent continuous values, rather than buttons, you might just read it directly every update
I've just tried doing this but it doesn't appear in the editor even when public, are you sure I can do it this way?
https://stackoverflow.com/questions/55992598/unity3d-new-input-system2-8-cant-reference-input-action-in-the-editor
var moveValue = moveAction.action.ReadValue<Vector2>();
this is specifically if you've enabled "Generate C# Script" on the input action asset
I don't use that, so I couldn't really tell you what to do there
I prefer to just use InputActionReference
Ah ok I have already generated a C# script
But I can still follow what you've said above and create actions for what I want to do?
Yes. Here's how I'd rewrite that script you shared
attach a Player Input component to the same object and drag a reference to it into the playerInput field
then, select the appropriate action for the InputActionReference field
now, you can just read its value whenever you need it
I prefer to use performed for button controls
for values, you just want the current value, whatever it is
But does .performed enable the value to change based on multiple buttons pressed? Thats the crux of my issue
the composite binding will correctly produce a Vector2 from the individual bindings
I would expect this to be fine. But I'm not sure exactly what your code looked like back then
note that it would fail to notice when you release the buttons, which is why you also used cancelled, I'm guessing
Just on a call but I will check shortly, thanks
kk
Well that seems to be working in that its reading the value and moving around, but I had to change one line to:
Vector2 moveInput = playerInput.Gameplay.Move.ReadValue<Vector2>();
However, now its not rotating
i still don't understand how you're doing playerInput.Gameplay
this would make sense if playerInput was the type produced by the Generate C# Script feature
e.g. when I turn it on, I get a class called Controls (because my asset was named "Controls")
show me your whole script again?
Because I cannot manually assign my playerInput as I cannot expose it to the editor, so I declare it in awake and access it that way.
Its working in that its moving around just fine but not rotating
I've been trying to fix it so my script has changed again but this is where I am right now:
https://pastebin.com/CFLPtJKy
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
wait
is "PlayerInput" the name of the generated class?
that's also the name of a component that the input system provides
perhaps that's where the confusion is coming from
that also explains why you were able to construct it, ah
Yes I believe so:
okay, that makes more sense now
I thought you were using the Player Input component
hence why I brought that up
so, movement is working fine?
i don't see any other actions here
Not exactly, it moves around up down and side to side which is great but I'm struggling to add rotation
what should make the player rotate?
Well tbh I played around with a few ways then deleted them so nothing right now.
I've added this so that it faces the direction it moves at least:
gameObject.transform.LookAt(lookDirection);```
you can also use LookRotation
Quaternion.LookRotation(movementDirection);
note that it also needs an "up" vector. If this is a 2D game, you'd want to give it Vector3.forward
but that looks fine as-is
It's 3D 🙂 I'll come back to it later. I may want to add a smoothing / lerp factor but at the moment the snappy sort of movement looks just like the oldschool PS1 games that I'm trying to emulate anyway so it works for now.
Thanks for your help, it definitely looks a lot better than listing out all the key bindings!
so for some reason this code is making the player accellerate upwards at some exponential rate non-stop once the player presses the jump button only a single time.
private Vector3 acceleration = Vector3.zero;
private void FixedUpdate()
{
acceleration.y -= gravity * Time.fixedDeltaTime;
controller.Move(controller.velocity + (acceleration * Time.fixedDeltaTime));
acceleration = Vector3.zero;
}
public void Jump(InputAction.CallbackContext context)
{
if (controller.isGrounded && context.phase == InputActionPhase.Started) { acceleration.y += 1f; }
}
Sorry if the problem is obvious, I'm new to unity
i'd call that velocity, not acceleration
although I guess you are kind of using it as an acceleration
this isn't an input system problem
controller.Move(controller.velocity + (acceleration * Time.fixedDeltaTime));
this is wrong
you're moving it a distance equal to its velocity from the last physics update
so if there are 50 updates per second and it moved 1 meter in the last update, it'll move 50 meters in this update
controller.move((controller.velocity + acceleration) * Time.fixedDeltaTime); would be more reasonable
ahhhh that makes sense, thanks :)
Hey guys, is there any simple way to set a keybind? I would like to read user input and then make it so that the player only jumps if the key is pressed which was previously inputted on the keybinds menu.
void Update()
{
if(Input.GetKeyDown(KeyCode.jumpKey))
{
Debug.Log("Test");
}
}
public void JumpKey(string s)
{
jumpKey=s;
}
}```
This is what I have currently, but it isn't working
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Events;
using UnityEngine.UI;
using TMPro;
public class Keybinds : MonoBehaviour
{
public Dictionary<string, KeyCode> keys = new Dictionary <string, KeyCode>();
public TextMeshProUGUI jumpText;
public GameObject currentKey;
public string jumpKey;
void Start()
{
keys.Add("Jump",KeyCode.E);
jumpText.text = keys["Jump"].ToString();
}
void Update()
{
if(Input.GetKeyDown(keys["Jump"]))
{
// Do a move action
Debug.Log("Jump");
}
}
public void JumpKey(string s)
{
jumpKey=s;
}
public void OnGUI()
{
if(currentKey != null)
{
Event e = Event.current;
if (e.isKey)
{
keys[currentKey.name]=e.keyCode;
currentKey.transform.GetChild(0).GetComponent<Text>().text = e.keyCode.ToString();
currentKey=null;
}
}
}
public void ChangeKey(GameObject clicked)
{
currentKey = clicked;
}
}
Is there anything wrong with this code where I would be getting this error:
The error occurs when I try and press a button to change a key
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
discord does not provide line numbers
something on line 47 is null
this is not an input system problem
Using a GameObject name as a Dictionary key is kinda 😵💫
You'll also want to make sure GetComponent<Text>() is actually what you want, as 95% of the time you're probably using TMP_Text instead
Hi. I set up touch actions. To get the touch position on the action, I added a binding with one modifier. Modifier is Touch contact and Binding is Touch Position. This basically works. Now I want to differ between tap and hold.
For hold interaction, the action is triggered after the waiting time and the binding has the value of the position
For tap interaction, the action is triggered when not longer hold then set, but the value of the position is 0,0
Am I misunderstanding something? I hoped to differ between those two types by using the corresponding interactions, but it only works for hold. Neither for tap nor slow tap, both do not have the vector2 then in the bindings value.
Hi did anyone knows why my mobile game exit when I press back button? I have "Input.backButtonLeavesApp = false;" in Start method in my code. So from what I understand it should'nt do that.
Hi, I'm currently using interfaces to get the events on the automatically generated input script. How to change the hold interaction duration using code? I want to be able to have a menu to change that value in game.
{
""name"": ""HorizontalMovement"",
""type"": ""Value"",
""id"": ""49033d8a-b0fb-4c61-b0be-e2cebf802eb0"",
""expectedControlType"": ""Axis"",
""processors"": """",
""interactions"": ""Hold(duration=0.4)"",
""initialStateCheck"": true
}
Is it possible to get the callbackcontext of any action that happens? Or do you have to get it from every single action. (I'm trying to get the control type of the last input action, indifferent to what it may be)
depends on how you've set up input handling
Oh, that looks interesting. Currently all inputs are handled like exampleInputSystem.exampleActionMap.exampleAction.performed += context => ExampleMethod(context);
I'm trying to get the device used, which I can easily do using the action context, but I was wondering if there is a way to get the context of the last action, no matter the action map, just so I didn't need to add a new method to every single input.
I'll look further into the onActionTriggered you linked
You're trying to draw control icons I suppose?
There's also the onControlsChanged event
Yes, I found a way using .current, but now there is a new problem, my dual shock 4 is pushing itself to the front, there seems to be a filter noise on current option that people say fixes this, the problem is, this option does not appear to exist in my settings window
As you can see, the option simple does not exist (Screenshot from the left is from the docs for the same version as mine)
Make sure the version of the input system you're on is the same as that screenshot - Oh
Haha, yeah, I made sure to check it, it seems to be around still, even on 1.5.1, while I'm on 1.4.4 https://docs.unity3d.com/Packages/com.unity.inputsystem@1.4/manual/Settings.html
I'm stumped on this one, a whole entire setting is missing
Okay, found something, through code, you cans till access the setting, but it seems to be deprecated, as it is "always enabled" now, which is simply not true, as the dualshock4 is listed as a noisy gamepad while still not being blocked by the filter
Well, I think I'll go with my "checking every input individually strategy" then, if it works, it works
It could still work, I just don't like forcing the player to unplug his controller if he wants to see pc icons
what do you mean "pushing itself to the front"?
are you talking about stick drift?
this wouldn't be blocked by a noise filter
noise is high-frequency randomness
stick drift is very low-frequency (well, zero-frequency!)
As far as the docs go, it's a known problem with dualshock4's. Its built-in gyro maintains a constant stream of inputs. The docs say that those input should be ignored by the input system as the dualshock4 is a marked as a "noisy" gamepad, but they're currently not. I've seen multiple posts on the forums talking about this exact situation, so it seems to be a bug or something of the sort.
oh, I misunderstood your post
I read "pushing itself to the front" and thought that meant a stick input
this is about the controller becoming the current controller
Oh, I see, sorry, I meant pushing metaphorically. No worries.
the option is also missing for me on 1.5.1
maybe you should ask about it on the input system forum
I don't recommend using the modifiers for that reason
Easier to have two separate actions and code it yourself
if(modifierAction.IsPressed()) {
}
else {
}```
You can configure the input system to ignore the SideAttack action if you input UpArrow + Z
however, it's not bulletproof: https://forum.unity.com/threads/surprising-input-consumption-behavior-with-modifier-d-pad.1424460/
it's an annoying loss of abstraction, but I might wind up doing this
at least to filter out the bad inputs
that's less bad than completely getting rid of the modifier bindings
According to youtube this is supposed to work. Why doesnt it?
this is not nearly enough information
are you using a Player Input component?
you need to have something that actually runs that function
Player Input, by default, is in Send Messages mode. It will look for a function named OnJump (optionally with a InputValue argument)
yours is named onJump
Hopefully simple question. If I have an InputAction MyActions, then an Action Map MyMap, and then an Action MyAction.
If I get it as a variable.
public MyActions InputActions;
I can then access the Action dirrectly.
InputActions.MyMap.MyAction;
How do I do that using just the string ID values if I have the instance of MyActions? I see FindAction, but what level is that returning(InputAction/ActionMap/Action). It seems It is the last Action, but how does it know which map to get it from?
Also side note the terminology here could have been a whole lot clearer, Calling every level Action is very confusing and really is not needed. Like just call them Collection/Map/Action.
Like you have a Collection of Maps, each Maps has Actions, and each Action translates/binds Inputs.
As it goes now you have an Input Action with your Action Maps, that have Actions with Inputs.
InputAction is an action
what is "MyActions"?
did you create this with the "Generate C# Class" checkbox?
Indeed
Yeah like I said
When you use the Generate C# Class option, it creates a C# class that has fields that correspond to all of your action maps and their contents.
What I need to know is how to get the Action/ActionMap from the string value,
or ID
If I have the InputActionCollection called MyActions
I love how this conversation is already getting confused because of all the Actions..
MyActions is not what is making this confusing
If you have an InputActionsAsset you can do myAsset["mapName/action name"] to get an input action
Controls controls = new();
controls.asset.FindActionMap("My Map");
controls.asset.FindAction("Some Action");
you can grab the asset and then find the map or specific action you desire
note that I just made up that first line so that the compiler wouldn't yell at me
I forget if that's how you actually use it :p
I work entirely with InputActionReference, personally
It is saying I can't do that with MyActions
because it's not an input action asset, yes
but it does have a field, asset, that gives you the asset
the InputActionAsset is the thing you configure in this window
Wrong type
Now do I have to do MyActions.assets["mapName/action name"] or can I do ["mapName"]["action name"]?
Look at the api
Think about it
It's not a mystery
All the types are spelled out
public InputAction this[string actionNameOrId] -> it returns an InputAction
if you want to retrieve the map, then the action, in two separate steps, use FindActionMap followed by FindAction
I have been scanning the Docs and I haven't even found where I can do .assets[""] yet
well, you won't find that in a single place
Great
.assets gives you an InputActionAsset
Love the new input system...
you then look at how you use an InputActionAsset
this is completely ordinary
the documentation for GetFoo() will not tell you how to call DoFooThings() on it
1: get the InputActionAsset
2: get the InputAction from the InputActionAsset
I see no reference of .asset[] and for me to infer that information without an example would mean I would already need to know that, which if I did I wouldn't be looking at the docs...
.asset returns an InputActionsAsset
that's unrelated to this
yes, because that's two steps.
That's why we're looking at the InputActionsAsset docs here
you wouldn't find a specific entry in the documentation for performing transform.parent.parent
you retrieve the asset, and then you query the asset for the action
Even then how does
public InputAction this[string actionNameOrId] { get; }
translate to being able to do
MyActions.asset[];
You just need the knowledge that functions and properties return data of a type and then you can look at the docs for that tpye to learn more
because you already know MyActions.asset returns an InputActionsAsset
you need to be able think in terms of datatypes
bruh I have been programing for 12+ years, I know those things, but there are 20 combinations of functionalities that this could be, and the one they are using isn't the clearest
because you are unfamiliar with the system, yes
This is quite clear
that is why you are here, asking questions
that is fine
I took some time to get to grips with the input system
If you've been programming 12 years you can mouse over .asset and deduce what type it is
then peruse the docs for that type
🤔
that's all that you need to do
Say this is quite clear, and yet 5+ hours of reading the documentation and testing hasn't lead me to being able to do this,,, sure.
You understand what data types are yes?
You know that if you want to deduce the length of a name of a GameObejct
GameObject x = new GameObject();
int length = x.name.Length;``` you wouldn't be looking in the docs for GameObject
you'd look in the docs for string / System.String
right?
this is the same
indeed
again, it's not unreasonable to not know what to do at first
but is is unreasonable to get angry at the system because you don't understand it yet
there's a modest amount of terminology to learn. I figured it out myself, but it wasn't an instant process, for sure
Okay first off, no where in docs is there a .asset reference. Second inorder to find that I would have to go down every variable/method/ect of the type in my IDE(which there are a lot). I am not saying how the functionality works doesn't make sense, I am saying to get here doesn't make sense, and the docs suck. As there are 5 different ways just for this api to do it, and they document one way well.
Plus the terminology still sucks
But all perspective I guess
i should probably ask why you're looking things up by string name when you've already got the generated C# script
you may be experiencing an XY problem
the intent of the generated script is to let you directly reference fields, rather than needing to use string keys everywhere https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/ActionAssets.html#auto-generating-script-code-for-actions
I am making an editor configurable action binding to my notification system. So I don't have to create a new script for each Action I have. Other places I do directly tie in, but for quick prototyping this is easier.
so you want to be able to tell a component about a specific action?
Is that what I said?
use InputActionReference
e.g.
it will let you pick any action from any input action asset you have in your project
you can then enable/disable the action and subscribe to the various events
Not what I need but thanks for the help
I don't really understand what you mean here, then.
I know and that is okay. I got what I need/asked for.
Gotcha.
I can certainly empathize with having trouble with the docs. I took a little while to figure everything out.
I dunno how I'd change them, but I'd do something, I guess
one small thing to keep in mind is that a lot of Google results will take you to random old versions of the docs
you'll want to make sure you're on the relevant version
Oh for sure. I mean even most video tutorials I have found are already outdated.
Video tutorials usually don't skip steps 😅
i'm impatient and constantly skip around videos
'cause I just want one piece of information
and then i get sad
how do i check what control scheme is currently being used
or more how do i detect if a controller is being used
nvm found a solution
what did you wind up doing?
i just made a seperate binding for the joystick instead of the mouse (i need the joystick to behave differently than the mouse) and check if the joystick was moved and if it was then set a variable to true
Okay InputActionAsset.FindActionMap("MyMap"); is returning null. The InputActionAsset isn't null, but InputActionAsset.actionMaps.Count is 0. Does anyone know if I have to initialize it or something before accessing it like this? Using a C# generated InputAction of MyAction also.
Well that doesn't seem to work from Awake() or Start().
public class tankBullet : MonoBehaviour
{
public GameObject bullet;
public float bulletSpeed = 100f;
Rigidbody2D rb;
Vector2 bulletPosition;
private PlayerInputs playerInputs;
public InputAction fire;
//have one bounce, and shoot from player tank
// Start is called before the first frame update
void Awake()
{
playerInputs = new PlayerInputs();
}
private void OnEnable()
{
fire = playerInputs.Player.Fire;
fire.Enable();
Debug.Log("fire button pressed");
//bulletPosition = new Vector2(bulletSpeed * Time.deltaTime, bulletSpeed * Time.deltaTime);
}
private void Fire(InputAction.CallbackContext context)
{
Debug.Log("fire! !");
}
private void OnDisable()
{
fire.Disable();
}
So i can't seem to get the fire button to work... just realized there was a help chat for this XD
You're reassigning it to the one from your generated C# class rather than the one defined on this script directly
Does the input action asset version have any bindings?
Oh sorry I see it
But you're not subscribing your function to the action anywhere
Also that Press interaction is not doing anything for you
(see the note it says)
I figured it out. I had originally called MyActions MyAction, and I was actually getting that, which had no Maps yets...
Is there an easy way to stop clicks going through when clicking on ui?
Handle all of your clicks with the UI event system and you'll get that automatically
ok press not doing anything and im not subscribing my function
all i am trying to do is get it to debug.log when im press fire button
you'd have to subscribe your function to the action if you want that
sorry noob here but in the script right?
yes
private void FixedUpdate()
{
Debug.Log("Move Values" + movement.ReadValue<Vector2>());
}
so this is basicly what im missing
but for fire
public class PlayerController : MonoBehaviour
{
private PlayerInputs playerInputs;
private InputAction movement;
private void Awake()
{
playerInputs = new PlayerInputs();
}
private void OnEnable()
{
movement = playerInputs.Player.Move;
movement.Enable();
}
private void OnDisable()
{
movement.Disable();
}
private void FixedUpdate()
{
Debug.Log("Move Values" + movement.ReadValue<Vector2>());
}
}
this one works and im guessing its because im calling for it to show up and the other im asigning but never calling on it to do anything?
or am im wrong lol trying to wrap my head around it
I do already.
you can do something like this yes, or subscribe to the performed event
then they won't go "through" UI
What could be the problem then?
okay thank you 🙂 i got it to show on debug log 🙂
idk you'd have to show your code etc
And explain what you mean about going through UI
how does shooting work
Sounds like your shooting is not using the event system
It's using the input system, are those two not connected?
not directly
I mean the event system is part of the input system but no just using the input system doesn't mean you're using the event system
public override Weapon.InputData GetValue() {
return new Weapon.InputData {
Fire = _shootAction.IsPressed(),
Cycle = (int) Mathf.Clamp(_cycleWeaponAction.ReadValue<float>(), -1, 1)
};
}
Alright, so I have to add a check to see if the mouse is over ui?
I'm a little confused
how are you clicking on ui elements
isn't your mouse cursor locked?
If you're shooting with mouse
No, it's top down
so you're clicking on a particular place to shoot there?
yes
Then you can do your shooting with the event system
So make an image that covers the entire screen?
you don't need UI
you can use events with your physics objects
for example the game background
Right
so like you could put a big invisible 2D collider behind everything
maybe in a layer that doesn't interact with anything physically
but you can use that to detect the clicks with IPointerClickHandler
and it'll even give you a world space position in the PointerEventData
you'll need a PhysicsRaycaster2D on your camera
already have that 👍
so looking through the unity docs what would I use to call say if fire button pressed do this. I can't find it in the docs. https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/ActionAssets.html page I was looking at the docs is so confusing sometimes
public void OnUse(InputAction.CallbackContext context)
{
Debug.Log("Fire was pressed");
}
``` i tried this but nothing happened think its because it dont have an interface so i think im in the wrong section of the docs as well
i got it working now had to follow a tutorial... haha i want to be able to not follow none of them
Hello, I have been trying to capture if my button is being read and if I can access the AR plane normals and get a value for average normal (for a process later on). First, of all just saying this now but the text on screen is used to debug values as my camera does not turn on when I run it on Unity Remote.
Now about the code: https://pastebin.com/NcQaEijV
This code is attached to my touchscreen button.
Now, I want to make it such that average normal is calculated when said button is held down.
Now let me share how I have done the Input bindings in this button and what the InputActionMap looks like.
This is my first time with using the new InputSystem. Also, this is my first time making an AR VR game using Unity so any suggestions for better debugging are welcome
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Platform: GooglePlayStore | Getting Trouble using the input field for regular text content. On the mobile device the keyboard comes up when field is selected but nothing comes up when typing, just a blinking cursor. Do i need to add script to remedy this?
Should work by default unless you have a script doing something
ohh ok will check that script then, thanks
what is the best practice for the new input system? currently using an actions asset https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/Workflow-ActionsAsset.html
so value is a variable for InputAction.CallbackContext? basicly instead of writing InputAction.CallbackContext for that now you can write value but just for the given method because the method is that type in this code
private void OnMovementPerformed(InputAction.CallbackContext value)
{
moveVector = value.ReadValue<Vector2>();
}
or is there more to value?
Is there a way with the editor, to check if a modifier is not pressed. Trying to do touch and bind mutually exclusive single and Multitouch, with modifier on contact and binding on delta. But I have to check for single, that touch1 is not contacted.
Hi, in Simulator mode, why does Input.GetMouseButtonDown(0) return true for me when I lift the mouse button? If I switch to Game mode it works properly. Here I added a simple test, and this Log appears 1. when I press the button, 2. when I lift up my finger.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("CameraClickCheck");
}
}
Is it a bug in the Simulator? I will build this and run on iPhone later, but I think it worked properly for me all the time.
I don't get it... you can see I'm holding the mouse button for 3 seconds and the I get 1x mouseDown and 2x mouseUp
I suppose I need to use "Game" not "Simulator" because something seems to be buggy. I'll check on deployed phone app later.
In "Game" view everything is beautiful:
Maybe I'll check in a brand new project first as well. It might be something in my settings.
Deployed to iPhone, everything works.... evidently that's a problem with Simulator only.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class InputManager : MonoBehaviour
{
private PlayerInput playerinput;
private PlayerInput.OnFootActions onFoot;
private PlayerMotor motor;
// Start is called before the first frame update
void Awake()
{
playerInput = new playerInput();
onFoot = playerInput.onFoot;
motor = GetComponent<PlayerMotor>();
}
// Update is called once per frame
void FixedUpdate()
{
//tell the playermotor to move using the value from out movement action
motor.ProcessMove(onFoot.movement.ReadValue<Vector2>);
}
private void OnEnable()
{
onFoot.Enable();
}
private void OnDisable()
{
onFoot.Disable();
}
}
```cs
no matter what I try this code just doesn't work. the error keeps saying
Assets\scripts\inputManager.cs(10,25): error CS0426: The type name 'OnFootActions' does not exist in the type 'PlayerInput'
and yet there is indeed an OnFoot in the action map
you're using the Player Input component, right?
yes
the player input component does not get fields named after the action maps and actions
you may be thinking of what happens when you use that "Generate C# Class" option
if you want to reference an action, use InputActionReference
it will allow you to refer to a specific action from an input action asset
ive been just following a tutorial
show me the tutorial
The first video in a series where we are creating a First Person game!
In this video we look at setting up our characters movement.
I've setup a Discord!!! and I would love to have you help me start up a friendly community where we can all help each other grow as game developers!
Discord invite link:
https://discord.gg/xgKpxhEyzZ
Can't wait t...
okay, yes, they're using the "Generate C# Class" option
extremely confusingly, they chose to name their input action asset "Player Input"
yeah the naming seemed off
this collides with the name of the built-in "Player Input" component
I would name your input action asset something else
maybe "Controls"
ok
then turn on Generate C# Class and proceed as usual
using Controls instead of PlayerInput
idk what that means but ill try the renaming first
oh yeah that
the tutorial may have addressed this
make sure you follow each step exactly
(it might be worth using the weird name, since it'll keep you consistent with the tutorial)
So uh
I pressed the power strip off button and of my project didn’t save anything I’m gonna lose my crap
hi anybody know why i get a null reference error for this
Vector2 inputVector = playerInputActions.Player.Movement.ReadValue<Vector2>();
I am trying to have the new input system control walk movement
You haven't saved your asset for starters
oh yeah still have the problem tho
what does that mean
I have no idea what i am doing
it sounds like you need some more basic experience here...
it is my first time using the new input system i have been doing it the old way for awhile
surely you've heard of the concept of "null" before, then..
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
you sure it is 900 lines
@supple crow https://gdl.space/wuhowumoce.cs
okay, yes, you need to construct an instance of PlayerInputs
line 300 is where the methods are called
see the example on this page
ctrl-f for "Auto-generating script code for Actions"
specifically, notice this part
public void OnEnable()
{
if (controls == null)
{
controls = new MyPlayerControls();
// Tell the "gameplay" action map that we want to get told about
// when actions get triggered.
controls.gameplay.SetCallbacks(this);
}
controls.gameplay.Enable();
}
i'd just construct it in Awake or something
I accidentally named my input actions thing PlayerInputs so which PlayerInputs are you talking about
yeah that is the input actions one cool
PlayerInputs is the generated C# class
I think i am to tired for this unless your willing to voice me
@supple crow have a good night or day. If you know any good tutorials on this or a video on doing key bind menu with the old input system send it to me ❤️
is there any way to use SaveBindingOverridesAsJson() without it clashing with other bindings?
like say if i had one binding for keyboard and the other for controller...
if i use SaveBindingOverridesAsJson, it automatically saves over both bindings
Under the new input system, how do we see what is blocking mouse input - the old system showed what you were hovering over, what gameobjects your mouse click interacted with etc
Early in the input system that preview wasn't working properly but it should be working in more recent versions iirc
what tool is that
Wdym by tool?
It's the preview window which is part of the inspector for the event system component
hmm, maybe in later Unity versions but not part of the input system package - i don't see anything in 2020.3
bummer yeah but maybe later i can try opening it in newer versions and see if there is info in the inspector
Newer Unity versions can use newer versions of the package
ok i will try that thanks!
Hello I am having issues in my 2d game
I am trying to find the mouse position it works when the mouse is being used as input but as soon as it switches to the controller it stops working
Here is my input controller ( PS this is an old version the mouse is position and not delta rest nothing has changed )
https://media.discordapp.net/attachments/497874004401586176/1098559654394613800/image.png
How do I get mouse position from controller or do I have to do something else
in what way does it "stop working"?
have you used Debug.Log to check the input values?
Stop working as it still points at the last position of the mouse for a while and then when I give it input it gets stuck on the bottom left of the player
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
It does give values yes but I am not sure exactly what values it is giving
Should I make another binding for the controller ?
What do you mean you aren’t sure?
Aren’t you logging them?
I am logging it but like it always returns similar values
public void Look(InputAction.CallbackContext context)
{
// Vector2 position = Mouse.current.position.ReadValue();
Vector2 position = context.ReadValue<Vector2>();
Vector3 pos = new Vector3(position.x, position.y, 0);
// Convert the mouse position to world coordinates
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(new Vector3(position.x, position.y, 10.0f));
// Calculate the direction vector between the player and the mouse
Vector3 direction = worldPosition - shootPoint.position;
// Calculate the angle between the direction vector and the positive x-axis
float angle1 = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
float angle2 = Mathf.Atan2(position.y, position.x) * Mathf.Rad2Deg;
shootPoint.rotation = Quaternion.AngleAxis(angle1, Vector3.forward);
shootPoint.position = Player.position + direction.normalized * 0.5f;
}
Similar when using the joystick (and distinct from the values the mouse gives?)
No both are different
The mouse returns the position and the right stick values are different
You’re reading the value of the input action, but it gives you mouse delta and joystick value, not mouse position
It gives you the amount of movement.
I have changed the mouse delta to position I am on phone Rn so I don’t have the updated version but the joystick one is the same
well, now you have two completely different kinds of bindings
And what does joystick value mean
mouse position is where your mouse is on the screen
the joystick value is just which direction the joystick is pointing
I would suggest having two separate actions: one for pointer position and one for pointer move
Ah I thought so
So I should make 2 different methods for taking input from these devices right ?
yeah
they're conceptually different
the pointer position action should just set a Vector2 directly
the pointer move action should add the input value to the existing Vector2
then, I'd just update shootPoint in Update
Ah I see thanks a lot
no prob
I will try that out in some time
hi, i have some doubts on the way I'm using the EventSystem and the MultiplayerEventSystem. I have a ui logically subdiveded into a sequences of menu , only in one of this menu i actually need to use a multiplayerEventSystem to support multiple PlayerInputs, so Ideally I 'm trying to switch between the EventSystem and the MultiplayerEventSystem and viceversa... How should I properly do this ?
currently I enabling/disabling the systems , but I seems i'm doing something wrong as I'm stepping on this kind of error
Hi everyone, a newb here just starting out with unity, i saw some documentation and videos online about the input system and by what i understood with what i have done i should have players spawning when i press different control schemes associated keys on my keyboard but it only spawns the first player, does this sound familiar to anyone? (and could that person help me please?) if need any screenshots i will provide, i just wouldn't know what to screenshot as of now, thanks in advance!
just to provide what i have done so far, i created a square, added a script to control it, added rigidbody, added player input and defined actions for multiple keybinds such as "wasd" and "ijkl" to move around, then i made a prefar with that "player" square, then i created an empty gameobject, added an inputmanager, then associated the player prefab to it, when i run the game the first time i hit any key from my keyboard creates a player that moves with the "wasd" keys but when i use the "ijkl" keys nothing happens
Question
I am doing a game that different input methods of the same key would do different things
for context, if I press spacebar twice - called the Boost button - in quick succession (with WASD key involved), the character will boost forwards at great speeds ("Boosting")
if I only tap spacebar once, it will do a hop ("hopping")
If I hold down spacebar, it will fly upwards ("flying")
In the Input System package, do I create three different entities each called "Boosting", "Flying" and "Hopping" separately with different interactions, or I can do with only "Boosting" and set up three individual interactions?
I would just use one action and handle that state machine in my own code
You'd need to create a custom interaction if you wanted to do all three of these through interactions
But I agree with praetor: i'd do this in code
so no screwing with the input system?
something like an if get button down instead will be better?
well, no, you'll still be using the input system
you'll just be deciding what to do with the input yourself
upon re-reading
as long as I hold down the designated Action Button (space in this instance), unity will constantly say it's pressed right?
define what you mean by "unity saying it's pressed"
if you do myAction.IsPressed() in Update, yes
GetKey vs GetKeyDown
GetKey and GetKeyDown are the old input system
yeah i meant like conceptually
with Input System, an Action Type Button when continuously hold will always trigger (like GetKey), instead of has to be clicked constantly (so unlike GetKeyDown)?
no it won't always "trigger"
whoop switched that around
doesn't matter.
It all comes down to how you are using the input system, but if you're trying to use event-based input handling no you won't get an event invocation for every frame while it's held down
you can poll the input in Update if you want.
I am a beginner. I didnt know what to do:
it works but this error shows up when i do left click, after i load a scene
pls tell me what i need to show you to help me :D
Looks like you subscribed to an input action but forgot to unsubscribe from it when your script was destroyed
that's not relevant
You're subscribing to the canceled event of an input action somewhere
and never unsubscribing
but after that i getting errors by clicking
Yes because unloading the scene destroys all the objects in the scene
hence the error you get because you never unsubscribed your event listener
so it's trying to run code on your script which was destroyed
smth like that?
no somewhere you probably have something like someAction.canceled += Something;
or someAction.performed += something;
you need to unsubscribe the listener
show your full script
what is the page calles i can upload the text?
here start with this error
this one will be easier
click this error and show the full stack trace
hmm that one is actually kinda weird 🤔
can you show your code? Maybe something weird is in your script
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Ok nah it's nothing there
Actually I think the problem is probably on your on screen stick
you probably have an event listener set up in the inspector to a destroyed object
https://hastebin.com/share/otipomehut.csharp and that is my other file i use
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Check the on screen stick inspector
it's not your code
?
wait that's a prefab
can it be because its blue? idk what that mean
is on the img
it is because prefab?
I'm not totally sure what's going on tbh
Does your canvas do some kind of DDOL thing
what is DDOL?
i do that but i testet it without that. but still the same error
and that is in my canvas
here is something
ok yeah looks like you have a DDOL object
and it's not properly enforcing the singleton aspect
so you're getting many of them
what components are on that?
Well that doesn't look related to your current issue but certainly looks like a bug
how i disable that?
Hi Praetor, could you maybe tell me something about my issue?
Input System Not Reading Release of Button I think?
(handled in another chat)
Can i get interaction from InputAction?
i don't know what that means
"Interactions" are just ways to transform the raw input
e.g. "Hold" only sends the performed event if you hold the button down for long enough
Hello there! We're using the New Input System in our project, but we're encountering an issue in Unity where it's detecting a PS4 controller on a computer even when it's not connected. Unfortunately, this is causing our character to move on its own, even though we don't have a PS4 controller connected. We'd appreciate any help in resolving this matter. Thank you!
how do you know it's thinking there's a PS4 controller?
have you checked the input debugger? iirc it's in Window -> Analysis -> Input Debugger
Yes, we check that windows
and appear the ps4 controller
The guy that have this problem when we work have a ps4 controller that he use to play, but is disconected when the problem happn
does it persist after restarting the editor? I know that I have a similar problem -- after connecting my wireless xbox controller to my mac, I get phantom inputs until I push on the stick
f we restart, the issue disappears, but it randomly reoccurs at another time, and we're afraid it may happen in the final product
if we connected the controller disappears too
is so strange
if we build "that" build the problem persist in the build
does it happen in other games, too?
is the only game that we have with new input system
dsnt happen when he normally play
so no other games (including non-unity ones) have any problems
only the game with the new input system
and only him
we have xbox controller and never happen
We believe that it's an issue with how the New Input System interacts with the PS4 controller but we are not sure
hm, yeah, that's weird -- so it happens in both the editor and the build, and it doesn't happen in any other games
(although maybe it happens in other games that also use the new input system)
Yeh maybe but we cant check that, we only work in one game with new input system
the weird is that only happen with a ps4 controller so we discard that the problem may with code or something. We turn off the ps4 support in the new input system and this stop the problem but we cant use the ps4 controller to play the game, we think that is not a solution TT
ScreenToWorldPoint
How can I read input from "back button" from android in new Input System?
Something is wrong with my custom composite. I don't know why, but it triggers buttons twice. Here is the code:
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
[DisplayName("Int Range Composite")]
public class IntRangeBindingComponent : InputBindingComposite<int>
{
[InputControl(layout = "Axis")] public int one = 0;
[InputControl(layout = "Axis")] public int two = 0;
[InputControl(layout = "Axis")] public int three = 0;
[InputControl(layout = "Axis")] public int four = 0;
[InputControl(layout = "Axis")] public int five = 0;
[InputControl(layout = "Axis")] public int six = 0;
[InputControl(layout = "Axis")] public int seven = 0;
[InputControl(layout = "Axis")] public int eight = 0;
[InputControl(layout = "Axis")] public int nine = 0;
[InputControl(layout = "Axis")] public int ten = 0;
public override int ReadValue(ref InputBindingCompositeContext context) {
if (context.ReadValueAsButton(one)) return 1;
if (context.ReadValueAsButton(two)) return 2;
if (context.ReadValueAsButton(three)) return 3;
if (context.ReadValueAsButton(four)) return 4;
if (context.ReadValueAsButton(five)) return 5;
if (context.ReadValueAsButton(six)) return 6;
if (context.ReadValueAsButton(seven)) return 7;
if (context.ReadValueAsButton(eight)) return 8;
if (context.ReadValueAsButton(nine)) return 9;
if (context.ReadValueAsButton(ten)) return 10;
return 0;
}
static IntRangeBindingComponent() {
UnityEngine.InputSystem.InputSystem.RegisterBindingComposite<IntRangeBindingComponent>();
}
}
When I press any button everything is fine and I receive the value. But when I up the key it return zero. But I am subscribed only to perform event
This is happening. It prints 2, everything is fine. But when I up the key it triggers for some reason
I don't see the same problem with Vector2Composite,for example. It works fine. You press the button and receive the value. But my composite behaves weird... It returns the value, but for some reason it returns 0 on releasing the button as well
since there is no support for magnitudes in your composite it will assume any value change is a "performed"
Oh God, thank you, Saver! I lost 2 hours and almost gave up
public override float EvaluateMagnitude(ref InputBindingCompositeContext context) {
return ReadValue(ref context);
}
did the trick
I'd probably do:
return ReadValue(ref context) > 0 ? 1 : 0;```
but maybe it doesn't matter
actually probably doesn't matter and/or yours might be better.
not 100% clear on how the magnitude thing works - presumably the interaction uses it somehow.
Yes, you are right, that will be better. Except, maybe, > 0. I've done >= 0 because I've replaced "ten" to "zero", so zero is a valid value too. -1 is invalid
Thank you again!
hi i'm new to unity and the imput system auto generated file is giving me about 20 errors a second and for the life of me i can't work out how to fix it
Sharing the error with the rest of us might help.
(the full error)
NullReferenceException: Object reference not set to an instance of an object
PlayerInput+OnfootActions.Disable () (at Assets/Input/PlayerInput.cs:263)
Looks like your script is the issue. Line 263 of PlayerInput.cs
without seeing the code there's little more I can say at this point
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
show your full script where you create the PlayerInput instance etc.
My guess is you haven't initialized it properly
E.g. you have some field
PlayerInput.OnFootActions something;``` and you're trying to use it without initializing it.
void Awake()
{
playerInput = new PlayerInput();
onFoot = PlayerInput.OnFoot;```
I'd expect that second line to be
onFoot = playerInput.OnFoot;```
@gaunt sparrow
note the capitalization
(also your link is broken I had to manually remove the / at the end to get it to work - for progeny )
i get an error when i change the capitalization
what error
'PlayerInput.OnFoot' cannot be accessed with an instance reference; qualify it with a type name instead
because it should be playerInput.Onfoot
again check capitalization
Have you been modifying the generated code file, out of curiosity?
feel free to use the auto suggestions that come up when you start typing - they are useful
hey im quite new to the new input system and i want to detect if the player is holding down their button but the way im doing things is confusing me.
anyone able to help?
are you using the Player Input component?
or are you using that "Generate C# Class" option
Only if you share what you have.
yes
yes i have.
okay, so that created a new class, named after whatever you input action asset was called
private void Fire(InputAction.CallbackContext context)
{
Debug.Log("YES");
}
so currently this only works when i click but i want it to work as if when i hold down the click it will keep running this function just like how
input.getkeydown would work
GetKeyDown only runs on the initial click but the way you'd do this is with Update
yeah so how could i recreate that? in the new input system
You are not going to get an event every frame with event based input handling
Use update
what do i use in update?
Either read a bool you set in the event, or poll the action directly
void Update() {
if (myInputAction.IsPressed()) {
}
}```
alright thanks let me try that out
or
bool pressed = false;
private void Fire(InputAction.CallbackContext context)
{
if (context.started) pressed = true;
if (context.canceled) pressed = false;
}
void Update() {
if (pressed) {
}
}
question when i call the funtion "Fire()" it asks for callbackcontext
what do i fill that with?
Fire(something)
so i don't do
if (fire.IsPressed())
{
Fire();
}
thats in my update funtion
Get rid of the parameter then
And unsubscribe it
From however you subscribed it before
and it will still detect my input?
Depends where you got fire from
yeah
Since we're polling in update now
Why would I tell you to do this if not
im just trying to better understand how it detects inputs
sorry
@austere grotto that works perfectly!
Cool
thanks so much i didn't realise how silly i was being about it
for a Big Prank
void OnMovement(InputValue value)
{
moveInput = value.Get<Vector2>();
Debug.Log("value");
}
My InputManager is set on Movement.
But in any weird thing, he didnt get anymore in this task.
i test it with a simble cube, but the InputManager didnt work
It could be a number of things. Have you called Enable() in the input object?
This assumes you're using a PlayerInput component on your GameObject in Send Messages mode. are you?
why is the started phase triggering only once
and it triggers canceled phase when closing the game
because started is when the onmove begins
well
i want when there is actual input, to set a starting position
and then calculate a direction
until there is no input
then you could look for performed...
Question. With the new input system. If I have multiple bindings for an action on the same map, one for M&K, and one for controller, can I receive each separately. Lets say I had two players, one on M&K and one on controller. Or would I have to have two separate maps that then is assigned to the player?
Yes look into:
- Control Schemes
- PlayerInputManager
I currently have this.
public struct InputAction_CallBack_Info {
public readonly InputActionPhase phase;
public readonly object value;
public InputAction_CallBack_Info(InputAction.CallbackContext context) {
phase = context.phase;
value = context.ReadValueAsObject();
}
}
What I am trying to do is save the last input action between frames, but the code above value is becoming null after the action canceled.
so
Player Input -> Fine
Player Canceled -> Fine
Playing doing nothering -> null
Also note I am only making that on Canceled/Performed. I see the Value is an object being made from referencing that memory location, and the input system is clearing that memory once the InputPhases are done?
If that is happening I could copy it byte wise, which the ReadValue(void* buffer, int size); could work for, but I don't know what to pass buffer, as context has the size of value, but no pointer to the start of the start address.
from the docs
All input values passed around by the system are required to be "blittable", i.e. they cannot contain references, cannot be heap objects themselves, and must be trivially mem-copyable. This means that any value can be read out and retained in a raw byte buffer.
The value of this property determines how many bytes will be written by ReadValue(Void*, Int32).
See Also
valueSizeInBytes
valueSizeInBytes
ReadValue(Void*, Int32)
So I guess I just need to know how to use ReadValue
How are you managing this struct exactly?
For the action when on Performed or on Canceled is called I create a new instance of the struct. This is then saved to a variable to be called later. Just since ReadValueAsObject is returning the reference to the Value instead of a copy, when the callbackContext is destroyed my value is also.
So I need to "readout and retain in a raw byte buffer" the value, but I am not sure how to get the int pointer for the ReadValue method...
Wait I guess I can use the start of the object ReadValueAsObject() returns for that?
if the object is just a regular C# object there's no such thing as "destroying" it
as long as you have a reference to it (you do?) then it's going to live.
CallbackContext.ReadValueAsObject is becoming null on it's own, and since this seems to just interface with c++ code. I am assuming what ever is destroying it is doing it on an unsafe level, so won't fallow normal C# behaviors.
Can you show your code? What you're saying doesn't really make sense
What kind of object is value pointing to when it's "fine"?
So here is capturing the callbackContext value.
input.performed += (context) => {
OnPerformed.Invoke(new InputAction_CallBack_Info(context));
};
input.canceled += (context) => {
OnPerformed.Invoke(new InputAction_CallBack_Info(context));
};
Using the value
public void Translate(object context) {
//_currentContextValue = ((InputAction.CallbackContext)context).ReadValue<Vector2>();
var value = (Vector2)((InputAction_CallBack_Info)context).value;
_source.AddVelocity(new Vector3(value.x, 0, value.y));
}
Wait sorry one step missed
I have a repeater between the top and bottom, that just saves the object being passed, sends copies every frame, but that never assigns to the saved value outside of the input call.
the InputAction_CallBack_Info object doesn't become null, just the object value.
Figured it out. On the canceled phase the value is null.
Hey, I have problem with GetBindingDisplayString() :
public PlayerInputActions playerInputActions;
void Start()
{
playerInputActions = new PlayerInputActions();
Debug.Log(playerInputActions.FindAction("MoveUI").GetBindingDisplayString(InputBinding.MaskByGroup("KeyboardMouse")));
Debug.Log(playerInputActions.FindAction("MoveUI"));
Debug.Log(playerInputActions.FindAction("Move").GetBindingDisplayString(InputBinding.MaskByGroup("KeyboardMouse")));
Debug.Log(playerInputActions.FindAction("Move"));
}
MoveUI and Move are set up exactly the same.
I don't know why the 3rd log doesn't return anything.
I also don't really know how to display the binding for a part of the composite accounting for the keyboard localisation.
If I want my player to enter a vehicle then control that vehicle, my first idea is to put a Player Input component on both my player and vehicle, but it seems that one Player Input component is tied to one physical player, so that's not an option. How are you supposed to do it? Tie the PlayerInput to the camera and manage spaghetti or something? What if there are multiple players?
is "Move" a composite?
ah, MoveUI is also a composite
Yes they just belong to different action maps
Deleted the action map in the editor, and now the action is correctly displaying. I guess I'll cut the string to display the localized inputs
Hey all, struggling to understand how PlayerInput's events associate to a specific action asset, currently I'm looking at a prefab that has a certain input action (A) asset assigned, in runtime it gets changed to another action asset (B) on start which has its own list of events that is different from (A)'s. If I change the action asset from (A) to (B) in the editor, the events list would change, and if I make changes to these events and toggle back to (A) , none of the changes made in the (B) events would be saved, and in fact, all the events in (A) are now gone. How does one edit the events associated to the action asset so they are carried over? It seems to work in runtime given things are correctly assigned when they are swapped. Thanks for reading this mess of a question!
I'm not sure if that's what you're looking for, but going into YourPlayerInputClass.asset should make the change on both afaik.
is there sth special i have to think of by using a multi tap? i have the same settings like for a "normal" input but when i add a multi tab interaction it doesnt trigger. By removing the interaction it triggers normal again by just pressing the button
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/ActionBindings.html#changing-bindings
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/ActionBindings.html#interactive-rebinding
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.5/manual/ActionBindings.html#saving-and-loading-rebinds
Thanks!
how to create a key combo to perform an action?
such as S + Space keys...
is it a binding /w a modifier?
I'll marry you if you answer!
apparently yeah, this is all that I needed...
although while I was reading other's previous convos in this channel,
they got advised to use 2 actions instead of an action with a modifier...
Does anyone know how to make a certain input a holdable button?
I’m making a platformer and it’s kinda ruining the flow of the game because I have to time my jump button every time I land, if I click too early it doesn’t input and makes for a worse experience.
Some help would be great
could you send a your code on how you did this please, i have to do the same thing but mines in vr
umm, no code required...
I didn't code it myself, I just used an InputActions asset...
here's how I set it up:
just make sure that the asset is assigned to the following script:
(which you can add manually to any GameObject)
the above mentioned asset helps a lot if you don't want to code.
however, I'm not sure how well that plays for VR-specific input...
I was able to get trackers input through it though!
@slender vapor Also...
I'm not trying to be a geek (whatever that means...), but!
you're using the Update method to manage input data...
isn't the whole idea of using the new input system is to avoid just that?
true, but i was scared that my imput wouldnt be checked if i put it in anything else so i just went for it
Hi, I have IPointerDownHandler, IPointerUpHandler, IPointerClickHandler implemented on my player's gameobject, but it only registers input when the gameobject is clicked, and not on every click wherever it is. I wanna know if it is possible to get all clicks with these interfaces
No that's not what those interfaces are for.
If you want to detect "background clicks" use a Fullscreen UI element in the background or something
I'm kind of stuck on how to fix this but when I run this script, it just sends a MissingMethodException for the function OnMove. Can someone please tell me how to solve this please:
https://paste.ofcode.org/XFGxhhRAPuPY5R4X44kTEX
This was done using the Input System (New version).
The correct parameter type for SendMessages callbacks is InputValue
You are using CallbackContext
I thought i could use these interfaces to solve my problem which is that when I click on a UI element, my game registers the click as if i was playing..
So if anyone knows how to differentiate UI input of game input, tell me pls
Oh, thanks
Pressing "f" during play mode always causes a one-time huge lag spike for a split second. This happens even after I get rid of all input system mappings for the "F" key. Does pressing "F" during play mode perform some other action that I'm not aware of?
okay so turns out that F maps to an editor shortcut. How do I disable Editor keyboard shortcuts in play mode?
in the Game Window there is an icon of a keyboard, click it before going into play mode or look at the latest responses in this post https://forum.unity.com/threads/unwanted-editor-hotkeys-in-game-mode.182073/#post-6701407 and https://forum.unity.com/threads/unwanted-editor-hotkeys-in-game-mode.182073/page-2#post-8160584
That worked. Thanks!
Very minor question, but would this type of input action be accepted by lets say, a playstation controller, an xbox controller, etc etc or is it just for generic type controllers? (ie those with no company branding.)
You don't need to use a composite binding for a joystick. You can just bind the Left Stick directly
And yes the point of it is to capture the left joystick of any gamepad
About local multiplayer using the new input system, when a new player joins and fires the "Player Joined Event" is it possible to bring the reference of the actual prefab it spawns?
I need to add the new player to a list someway...
The event includes a reference to the newly spawned player
See the PlayerInput parameter
The GameManager.PlayerJoined? I created that method
yes
It should have a PlayerInput parameter
it has not
You need to add it
or to be more precise I have no way to reference it
public void PlayerJoined(PlayerInput newPlayer) {
// etc..
}```
then reassign it in the unityevent again
from the Dynamic list
ok
It doesnt works
public void PlayerJoined(PlayerInput playerInput)
{
playerCount++;
//
string playerId = playerInput.playerIndex.ToString();
playerInput.gameObject.name = "Player Entity - " + playerId;
Debug.Log(playerInput.gameObject.name + " JOINED");
playerControls.Add(playerInput.gameObject);
}
Here is the code
it prints Player Entity - -1 JOINED
Looks like it's working
Since the reference of that method its a prefab I'm operating on the prefab and not on the clone it spawn when a new player joins
did you plug the prefab into the parameter in the inspector? Or did you do what I said above and assign it from the dynamic functions list?
Sounds like you did the former, which is wrong
show a screenshot
Yeah you right, I forgot to use the dynamic feature
Now seems good, guess I can use the id to discriminate the various inputs
Thanks man!
does anyone know the keybind for making an IEnumerator
TLDR: Do input interactions work when using the generated c# class?
I’m using the auto generated c# class because I want to use the SetCallbacks method. I’m also using the PlayerInput component because I was to use the local coop split screen features.
This is my Awake method.
private void Awake() {
_playerInput = GetComponent<PlayerInput>();
Controls = new Test.StarterAssets();
Controls.Player.SetCallbacks(this);
_playerInput.user.AssociateActionsWithUser(Controls);
Controls.Player.Enable();
}
This is mostly working, I have two players in the game one using keyboard control scheme, the other using gamepad control scheme. The issue is I have a “Hold” Interaction of the Jump InputAction, but it is having no effect, the player will jump as soon as the button / key is pressed.
Is this a limitation of using the generated c# class, or (more likely) am I doing something wrong?
the player will jump as soon as the button / key is pressed.
What does your code look like that handles jumping?
I think you're just doing something wrong
for example not checking if the phase of the input action / callback context is the peformed phase
Yes this was it, thank you
One other thing would be do you foresee any issues with using the AssociateActionsWithUser method to link PlayerInput to the generated class instance, which would prevent a split screen game from being made?
not really - but I would try to see if there's not a way to do it with only one InputActionAsset instance
e.g. is there a way to use the generated API with the InputActionAsset on the PlayerInput ( _playerInput.actions)
I've had a look but I don't see a way to do it, I tried adding a new contructor to the generated file and passing in _playerInput.action instead of generating a new InputActionAsset from JSON, but it didn't work and presumably it would have been overidden anyway next time the InputActionAsset was changed
Morning
I know natively Unity Input System cannot preempt an input and I need an extra script doing it like a middleman
I wanted to do something like "if Melee and Shoot button are pressed together, the character neither shoots nor melee, but uses an another weapon in their preset"
In this extra script, what should I do such that both weapons keep their functions, but does sth else entirely when a specific press is done?
(as in, does this middleman script do things like
If (MeleeIsPressed || ShootingIsPressed)
{StartCoroutine(useAnotherWeapon)
Else if (melee is pressed)
………
Or other approaches?)
old or new input system?
im not yet familiar with the new one, but if using the old your suggestion is right about what i'd go for/ (might works the same with the new one but i couldnt tell you).
if (MeleePressed && ShootingPressed)
{
other weapon
}
else if (MeleePressed)
{
mellee weapon
}
else if (ShootingPressed)
{
shooting weapon
}
alternatively you could nest if statements but I Preffer not to if possible
important is the use of '&&' rather than '||' though like in your example, or it will use the alternative weapon in either one or both are pressed, resulting in the inability to use the melee and shooting weapon on their own.
Ah yeah whoops
Forgot about that
But yeah I think this is the general approach I suppose
you MIGHT have to implement a time buffer tho. Im not sure from the top of my head how this will respond, but if youre doing this with OnKeyDown the timing to match both keys is incredibly tight i'd assume
so i want to add a crouch input to the first person template when creating a project. and i did this:
{
CrouchInput(value.isPressed);
}
public void CrouchInput(bool newCrouchState)
{
crouch = newCrouchState;
}
along with some other code in the FirstPersonController.cs, i hoped this would work but it didnt. did i do anything wrong with the input system?
along with some other code,
That's important code to share
also an explanation of what you mean by "it didn't work"
what were you expecting to happen and what happened instead?
that's definitely a load-bearing "other code" :p
should i post the entire code or just the things i added in?
when i say it didnt work i mean i pressed LeftControl and nothing happened.
i expected the camera to move down
are using the Player Input component?
there are several ways to get input into your script
let me check
is left control bound to the Crouch action?
Is your PlayerINput component attached to your player?
Is it set to Send Messages mode?
and is the action named "Crouch", exactly?
'cos SendMessages demands an exact match
i don't like it, for that reason
magic strings
im using player.input
what is player.input?
uhh
there is no such thing by that name..
idk what im supposed to look at exactly
be specific and explain to us what you're doing because we cannot read your mind or see your screen
idk what to look at
start with your player object
does it have a PlayerInput component on it?
if so show us a screenshot of the inspector
you mean the BasicRigidBodyPush.cs ?
where do i see my player object in unity
Idk presumably it's a prefab or in one of your scenes? You tell us
Again we can't see your project
i just created a new project and used the first person template
lemme take a screenshot
anything here?
the player is probably not the Environment
does this first person template come with any instructions for using the input system?
i am unfamiliar with it
does it, out of the box, let you move around?
okay, so it's in Send Messages mode
now, show us the input action asset
the list of actions. looks like this.
double click on the field
okay, so you have no Crouch action
the input system cannot guess that you wanted to be able to crouch by hitting ctrl
indeed
action type value or button
you want a button, it sounds like
i would capitalize "Crouch"
it should not matter -- it's gonna get PascalCased when turned into the method name it looks for
i wrote crouch in small letters in the code
but you might as well be consistent
seems good to me
i think you need to add the Press interaction and set it to trigger on press and release
is it possible to read the joystick value directly using an input action asset?
i.e. my action 'Move' has a Left Stick [Gamepad] binding
the move action is a vector2 value
add an InputActionReference field, assign the appropriate action, and then do myField.action.ReadValue<Vector2>();
of course, the action must be enabled -- if you have a Player Input component, it might already be turning the whole action map on for you
it's reading only vectors normalized to 1, i need the precise vector
yeah I'm doing var input = _inputActions.Player.Move.ReadValue<Vector2>();
Oh, you’re using the generated C# class
yep
nope
Should it be returning values like -0.123,0.348 etc when you set it up like this? because then my steam controllers layout may just be the issue here
Ah, maybe your steam controller is set up to do that
I haven’t tried using mine in a while
Hmm so normally it would return non normalized vectors this way?
I don't really have another controller to test that with
before i deep dive into the steam controller settings, its pretty confusing which layout it's using in the editor anyway haha
I've not got the foggiest idea as of what i'm doing here
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.Scripting;
[Preserve]
[DisplayStringFormat("{modifier1}+{modifier2}+{button}")]
public class NewBehaviourScript : InputBindingComposite<float>
{
var action = new InputAction(type: InputActionType.Button);
action.AddCompositeBinding("ButtonWithTwoModifiers")
private void Movement_performed(InputAction.CallbackContext context)
{ StartCoroutine(); }
I am trying to make the script read multiple inputs at once and perform specific actions, then make it call an another script's coroutine
but i have no idea how to do that
what worked for me is setting the desktop layout to a gamepad layout, then installing the xbox 360 driver by enabling xbox support in big picture mode's controller settings, then added the unity editor as a steam game, and launched from my library
now im playing Unity and it works as a xbox controller
😵💫
cursed
Im using the new input system with the invoke unity events method but with the analog it only reads one axis at time even if I store a vector 2
And the coordinate I get is either 0 or 1, nothing in between
How can I solve this?
what do you mean "only reads one axis at a time"?
do you mean it gives you [1,0], [0,-1], etc?
yes
Also I'm trying with the SendMessage behaviour but seems that some methods don't get called even if the name is right
i vaguely recall Pass Through behaving differently...
i think this question fits better here... how do i toggle the "use reference" button from an InputActionProperty via script? cant find a means to do so.
edit: I couldn't find a solution. this "use reference" variable is the variable m_UseReference in the InputActionProperty.cs in the read only input package. It is a private serialized variable. My solution was to duplicate the file and put it in my own projects assets, and swap the private variable to a public one. This will not hold up when the input system gets updated (well rather, when InputActionProperty gets updated), but since this is a major part of it, that shouldn't happen until another major version.
I use the new InputSystem. I mapped a controller properly to InputActions in an InputMap. When I navigate the menu with a controller and enter the game, I can't use the controller anymore, only the keyboard. And the same happens the other way round. Any Idea what could be the culprit here?
The Debugger shows that as soon as the character is spawned, a new input user is created and given the other input device. How do I prevent new user creation?
Found it, had a second PlayerInput
Hi, not sure if it fits here but it's somehow related, let me know!
I have a Button class that I need to press while talking:
public class RecordAudioButton : Button
...
OnPointerDown(PointerEventData eventData)
OnPointerUp(PointerEventData eventData){
//save recordings
animator.SetTrigger("Normal");
}
It has a animation transition with its animator.
Everything works fine in the editor, however on ios the animator does not go back on Normal (but stays "pressed" ) until I click anywhere else on the screen.
All the code runs with no errors and the setTrigger is called. Just the state doesn't change
edit:
I fixed by calling a coroutine that tries to setTrigger normal until the state is pressed. The issue here is that while inside onpointerup something is still setting the trigger to pressed. Any ideas on how to make it more elegantly?
any way to lock cursor to center on android? the cursorlock dont seem to work on android.
For first person game
Are you using a mouse on Android?
Yup
I don't know if Android supports cursor locking
I mean some people did it and i was curious
hey guys, i have a PS5 controller, also known as the dualsense controller, and for some reason the interact action is not responding to when I press the X button, but the left stick (in another input action) is working perfectly, signifying that the controller is connected. What's going on?
how are you handling the input in code?
Well i did an event system
should I send that part?
//in awake
playerInputActions.Movement.Interact.performed += Interact_performed;
//out of awake
private void Interact_performed(UnityEngine.InputSystem.InputAction.CallbackContext obj)
{
OnInteract?.Invoke(this,EventArgs.Empty);
}
so this is in my game input CS
Have you tried putting Debug.Log directly in this function as the first statement?
huh, no actual
let me try that
also, highly recommend against using the EventArgs pattern in Unity
it allocates unecessary heap memory aka garbage
which will trigger garbage collection - the bane of game performance
Yeah it does give the debug
ok then the input is working
Im just following along a tutorial so nothing really I can do RN
the problem lies with however you're setting up the event handling for Oninteract
Im doing exactly how the tutorial does it
id love to cause im going insane, i already checked my code and their code thrice
shoudl I send here or elsewhere?
here is fine
//in start
gameInput.OnInteract += GameInput_OnInteract;
//not in start
private void GameInput_OnInteract(object sender, System.EventArgs e)
{
Vector2 moveDir = gameInput.FindMovementVectorNormalized();
Vector3 actualMovement = new Vector3(moveDir.x,0,moveDir.y);
if(actualMovement != Vector3.zero)
{
lastInteractDirection = actualMovement;
}
float maxInteractDistance = 2f;
if(Physics.Raycast(transform.position,lastInteractDirection,out RaycastHit raycastHit,maxInteractDistance,countersLayerMask) && raycastHit.transform.TryGetComponent<ClearCounter>(out ClearCounter clearCounter))
{
clearCounter.Interact();
}
}
so this is the playercontrollerscript
basically all the interact does is send a debug
why not again put a Debug.Log at the first line here
insiede GameInput_OnInteract
maybe your raycast is just not hitting anything
this is how you debug
keep checking where the code is getting to
and when you see where it stops - you found your issue
I debugged that previously actually, I know it hits, just gimme a bit
if the raycast hits then everything is working fine, no?
what exactly isn't happening
it isnt telling clear counter to send the debug
let me restart the editor just to be safe
ok well - add more lofs
i swear if its bugging out again
restarting the editor is unlikely to help
i dunno, sometimes doing a turn off and a turn on really fixes these issues
that didnt
OK, added that debuglog