#🖱️┃input-system
1 messages · Page 40 of 1
So much closer now, just have to get the InputActionMap state right between the "menus" and the panels that are always on
Many thanks again so close now
awesome!
Probably create some form of state manager that a bit more verbose then the stak I have now for UI lol
Hello, I'm trying to update the touchscreen controls to the new input system, specifically a press and drag input (Imagine something like Angry Birds), but I haven't been able to find examples online about it
Before I was using Input.touchCount > 0 inside the Update loop to detect the touch, and Input.GetTouch(0) to get the information about it
I'd like to see if there is a way to use the new input system to take the code out of Update() using the Actions
hey guys, complete noob here. i want to make a control scheme like the ones found in sessions or skater xl, a thumbstick that controls a limb. where would i even start? what that even called? im sure IK is involved... that about the limit of my understanding at this point
to put it another way, motion that is not a canned animation
hey how do i get a controller working for unity
Hei
hello
add the Controller component to a capsule or whatever shape you want the player to be then add your own control script, WASD arrow keys or whatever you desire
if you make the camera a child of the player object it will move the same way the player does
Anyone here knows how to split the keyboard so that the input manager spawns a prefab for each part of the keyboard ?
@gritty tide yes. There's a good way and a bad way.
I wrote this a while back but it probably still works.
@west oracle Thank you so much! I need that for a jam I'm doing right now and for future projects. I was planing on making a way worse solution 😅 . Props for such an elegant one 👍
I guess there is no licence on this right ?
Go for it :)
How can I mention you ?
Link to Unity forum account (Fenrisul)
ok great!
I can't remember if I put MIT license or WTFPL license on that one lol
Either way, is free to use :)
I made a unity co-op template and that was one of the last parts missing so...
Yup... It was a big oversight from Unity heh
it even works for more than 2 users! nice
Ya - it don't care heh. Feels a litttttle clunky but it gets the job done :)
👍
if i fix their positioning for one res
theyll be broken in the other one
im using this asset
Hey, why doesn't OnPointerDown fire on mobile with the new input system? It fires when I click, but not when I tap through unity remote. I don't think it's a problem with unity remote because the exact same code works fine (both clicking and tapping through remote) when I switch back to the old input manager
aaaand i just built it and it turns out it does work..
being unable to quickly test through unity remote is going to be a hassle, is there any fixes/alternatives?
https://forum.unity.com/threads/new-input-system-and-unity-remote-5.735968/ answering myself again, ig not 😔
is the rollaball tutorial a good tutorial to learn about the new input system?
is there a way to inverse the horizontal input when the "s" key is pressed (or the vertical input is negative)
@bitter ivy You may not mean 'inverse' Inverse of -1 is 1/-1 which results in -1 . Do you mean change the sign from negative to positive.
If so, multiply -1 by -1 will return +1
Ah I’ve got a solution now thanks
This enrages me so much.
@neat pebble https://forum.unity.com/threads/best-practices-getting-started-tutorials.875818/ and #🖱️┃input-system
yea 😦 gonna revert back to old system for now
my unity forum acct is Fenrisul
so you'll see my similar regards in there lol
its KIND OF worth mentioning that you can actually forward input system events from Android/iOS --> UnityEditor, but it wont do video
which is like... why?
ugh yea.. not really any viable workarounds ._.
I might do it before they do again
@prisma notch tons of thoughts. Want any particular use case reasons?
@west oracle well, what matters to me the most is: a) Windows (using controllers) and b) mobile using joystick-like touch controls for in-game, and touch presses for menus
InputSystem doesn't support UnityRemote
So that rules out Mobile if that's part of your pipeline
InControl has a stronger implementation in my opinion. It has very little bloat and is super easy to use.
Onscreen controls work fine as well
Rewired has more profiles for various different devices but it's harder to wrangle
InputSystem has the most robust support for custom input including unique force feedback devices, etc. It just exposes raw byte code or allows virtual devices if you ask it to.
I personally use either InControl or InputSystem, and only rewired if it's part of an inherited project
Hello
In the INpput System Package how can make bind more tha one key to the same action?
i mean i want to binding an action to different inputs like gamepad and keyboard too
nevermind i got it!
delta means "change"
mouse delta is the change in mouse position from the previous frame
Hey ! I used a custom Inputs system and I'm making a multiplayer game.
I have a script on my player GO and i want to do that :
if (Controls.instance.jump + gameObject.name);
I have made keycodes named like this "[Action]P[playerNumber]. and my player is named with "P[playerNumber]
Exemple for the jump key of player 1 : JumpP1
And my script it's a generic script that's on all of my players
If I use the built-in Input Manager i can do that :
if (Inputs.GetButtonDown(Jump + gameObject.name));
The new input system has a whole recommended way to do this
you use PlayerInput
and PLayerInputManager
but if you must do it your way, you just need to fetch the InputAction with the name you want
so like... Controls.instance.FindAction("<your inputaction name here>")
something like that
Find action does not exist...
I use a custom Input System for make a InGame Remmaping system
Ok well I don't know how your custom input system works
Does it have a way to find an action by name
If it does, use that way
This is Controls with a singleton
Yeah... you're going to need to revamp that a bit if you want to dynamically use strings to address stuff
instead of using a bunch of public KeyCode fields
maybe make a Dictionary<string, KeyCode>
then you can look them up by name
I don't know what is a Dictionary... I'm going to check on internet...
Thank you anyway @austere grotto
How do I override the processors on a binding at runtime in the Input System? I'm using an Input Action Asset and generating a C# class for it (referenced here with _input).
Right now I have the following code in my Start() method for my PlayerController class:
var lookBindings = _input.Play.Look.bindings;
var rightStick = lookBindings[0];
var mouse = lookBindings[1];
print($"{mouse}, {mouse.effectiveProcessors}");
mouse.overrideProcessors = "InvertVector2(invertX=true,invertY=true),ScaleVector2";
print($"{mouse}, {mouse.effectiveProcessors}");
According to the console, mouse.effectiveProcessors is set to "InvertVector2(invertX=false,invertY=false),ScaleVector2" before my override assignment and does actually change after the override assignment, but there's no actual change in mouse behavior.
I've tried enabling the Play action map before and after the override call, as well as assigning to processors instead of overrideProcessors, both with no difference in effect. I've also unsuccessfully tried using _input.Play.Look.ApplyBindingOverride(1, mouse).
Any ideas?
Hey guys! I'm confused about something.
What are "optional" and "required" options for in the control schemes configuration?
Hiya, using the new unity input system, the mouse scroll wheel seems to be super intermittent?
Like, it often just doesn't register input at all. It's not an issue with the mouse as it's scrolling perfectly fine in Discord.
How are you using it in code?
Hello Everyone ! Trying to use the Editor Unity Remote on my Android Phone (Xiaomi Mi 9T Pro). I have Unity Remote 5 installed on it, and when I enter play mode it's displayed correctly on my phone. Although, I'd like to be able to interact on my phone to send touch inputs (i'm using the new input system). It doesn't react when I touch my phone, any ideas why ?
PS : note sure this is the correct channel for this question, if so redirect me please 🙂
I'm doing the InputAction.ReadValue<Float>() thing.
- When and where are you calling that?
- Where are you getting the InputAction from?
So, i'm reading the value every frame in an update on the obj that has the InputAction variable.
When I'm scrolling it's usually 0 but it's meant to be either -120 or +120
but it's only accurate sometimes
often it just stays at 0 even though I'm scrolling
Oh wait, I've just realised I should've been using action callbacks instead. Fixed it now thx :)
Perfect place for it! The new InputSystem does not support Unity Remote at all. 😦
Hi guys, anyone familiar with the XR Controller Inputs?
Need to change XR Ray Interactor to listen to the stick instead of gripPressed
can someone help me get the camera to work with the controller
all the controls work fine but right now i cant control the camera with the right joystick i can only use the mouse
Is there a "catchall" event for InputAction that fires for any of started performed and cancelled?
I want to simplify this:
map.Strafe.started += HandleStrafeInput;
map.Strafe.performed += HandleStrafeInput;
map.Strafe.canceled += HandleStrafeInput;
Any ideas on how to prevent a duplicate binding? I'm using PerformInteractiveRebinding to make the process interactive
I could loop through all actions and subsequent bindings, but that feels inelegant
How the hell didn’t I think of that, I’m already excluding mouse actions with that 
Thanks mate @west oracle
no problem lol
but also I agree it should be smarter
i haven't poked the very latest inputsystem stuff yet, did ReneDamm finally get Serializing working for remapping?
Ya, I think this way I still need to loop through all of my bindings
should be easy enough to write an extensino method to do that
.WithIgnoreExistingBindings(map)
Yeah, that’s true, implementation should be easy enough
(any response to my serialization question? legit interested in people trying to use stock InputSystem)
I'm making a game with keyboard button inputs aswell as like, touch controls if it's played on a phone. Where do you typically hold the functionality of these inputs? In a separate Script with all the inputs like some Input_Manager.cs or is there some better way to do this so it fits to each scenario (so in a menu up and down works differently than in a battle scenario)
@bitter talon create different action maps to change between different situations of input like for player and UI
But my question is how to switch between different action maps in runtime?
So I grabbed rewired, although I'm not sure I can ask questions about it here.
but I have
Player.AddInputEventDelegate(OnMoveHorizontal, UpdateLoopType.Update, InputActionEventType.AxisRawActiveOrJustInactive, "BF_Horizontal");
Is there a way to make this only on press and also not have the value be a float going to -1 or 1
but just -1 or 1.
{
return playerControls.Player.Crouch.started;
}
public bool PlayerCrouchingButtonReleased()
{
return playerControls.Player.Crouch.canceled;
}```
is giving errors 'inputaction.started can only appear on the left side of +='. I don't even have a +=, so why is it doing this? Is there a better way for checking if the player is holding the button or not?
Those are events, you’ll need to bind handlers to them
@pulsar mist
something like
void Start()
{
playerControls.Player.Crouch.started += PlayerCrouchingButtonPressed;
playerControls.Player.Crouch.canceled += PlayerCrouchingButtonReleased;
}
public void PlayerCrouchingButtonPressed()
{
// do pressed stuff here
}
public void PlayerCrouchingButtonReleased()
{
// do released stuff here
}
private void Awake()
{
input = new InputMaster();
input.Player.Run.performed += _ => IsJumpKeyPressed();
}
public void IsJumpKeyPressed()
{
print("Hi");
}``` I am new to the new Input system but it doesn't seem to work
have you enabled the input?
ie
void OnEnable()
{
input.Enable();
}
void OnDisable()
{
input.Disable();
}
@smoky jewel
@waxen plover thanks I forgot
I read the docs but am still not sure. Is action.canceled the same as OnKeyUp?
@smoky jewel sometimes! 😛
I don't want to admit how many times I've forgot to do this, so I won't 😛
How can I set up num keys ?
You would set each one up as a separate input action
I did it. I just had to add a scale to my bindings with the same number as a key then round it from a float to an intint numPress = Mathf.RoundToInt(input.UI.NumKeys.ReadValue<float>());
Is there any way to disable and enable certain action maps?
how to make my button act as jump using the new input system?
private void Awake()
{
input = new InputMaster();
input.Dialog.Vertical.performed += eventTest; }``` How could I make this work?
Yes ActionMap has enable and disable methods
If you're using the generated code the action maps are all disabled by default
@austere grotto what do you mean by generated code?
In your inputs action Asset
You have Generated code checked right
And it makes the class called InputMaster.cs for you
?
yeah
That's the generated code
When you do new ImputMaster()
All of the action maps on that are disabled
Until you enable them
Hmm really?
would this make them enabled?
@austere grotto well thanks
Do you have any idea on how I should face the problem above? the unity event thing*
Oh..
That's weird I've never tried to add a UnityEvent asca listener like that
Does that work?
Normally you just write a listener method
When my controller is connected my inputs get a little weird. The left mouse button no longer works but the right trigger does, the south controller button works while the space bar doesn’t. The rest of the keyboard and mouse work and the rest of the controller don’t work.
Without the controller connected the mouse and keyboard work great. Any thoughts on what I could look into for this?
How can I switch between different action maps in runtime please?
@bright kite you can Enable and disable them
When I import the Input system into URP, why does the Simple Demo not work?
How in the world does my render pipeline have anything to do with input?
It doesn't
what's the "Simple Demo"?
Is that part of URP? Or part of Input System?
in the input system how do i make something work exactly like old GetAxis
nvm i found what i want
You can replicate old GetAxisRaw perfectly but not GetAxis
GetAxis has some built-in smoothing behavior
hello, i accidentally installed input package from package manager but i need to use input manager
i removed that package but cant revert to input manager
how can i do that?
in project settings there is an option to switch between the two
I have a quick question when it comes to the UI and the New Input System
Does the input get read if there is no UI selected?
I understand how everything should work when you are navigating the UI using keyboard controller
But I want to make it so that if you move the mouse then Nothing should be selected until the mouse is over a UI element
Or should I just have it so if the mouse moves over a different UI element that one gets selected instead?
I just don't want to end up doing something that is overly complicated like in some other projects that I have worked on.
HELP, i spent 1 days 2 weeks ago to get the system to work, NO progress, and now i try again and NO scucces
you want me to bring time back?
So the probloem is this I asume everithing I do is right, i mean I did coppy everithing from the Warrior example project but the system just isnt working
do you have scripting experience?
yes
did you change any object names?
I coppyed by looking and creating my own version of things "Asset, Movement"
One thing that stand out from the Example project and mine is this "Device" something assinged to it
but did you touch the scripts because if you change names of stuff then in the scripts you copied you need to have that name changed
I did not coppy the scripts, i coppyed the code that is in there, and put it in my scripts
To go right to the rood of the problem, from what i found out, My callbacks are not called
From my understanding of the Imput System this is how it shoud works
I dont understand this part, why dose the Example has a Device detected, and Mine has None
This is the code, and the function OnMovement is placed on the Movement callbaack from the imputAction ^screnshot UP
Error says no physics material found
Or rather, warning.
the error is from the controller, more precisily " Collider and rigidBody interaction" and has nothing to do with the imput system 😦
Found the solution for the problem, IDK no one mention this anyware, You have to create a ControllSchema, and wen create add the device necesary fot the Schema. In my case, a Keyboard/Mouse controller requaer a Keyboard and a Mouse as Device
Hope this helps someone!
Hey friends, came across an interesting article about reducing the number of times unity draws the scene: https://secretlab.institute/2019/06/14/power-saving-in-unity-for-non-game-apps/
Part of the problem they encounter is the input being tied to update methods.
I was curious if the new input system would take this part out of the equation?
@zinc igloo you can poll the new InputSystem manually. It is not tied to any particular Update method.
Hey everybody ! I have two simple questions: Would you say the InputSystem is solid enough to be used in a commercial project or I am better off with an asset like Rewired ?
Second question: Last time I checked, the Input System was not working will with local multiplayer (there were no simple way to deal with it) is it any better now ?
Thanks !
is there any way of treating inputs on vector2s like button presses? e.g. pressing w makes the variable (1, 0) for a single frame vice versa
I'm struggling to get the ball to move in the "Roll-a-Ball" Unity learn project. I've tried changing the float speed = 0 to just float speed, inserted a Debug Log to the code, and changing the behaviour input on the Player Inspector
Any ideas as to why the ball wouldn't move?
What's speed set to in the inspector
can someone dm me rq i need help
10
Somehow, I think the script is not communicating with the project file. I have linked the script to the player in the game. Not got a clue
how can I create an "invisible button" that gets a callback every time it's pressed or held with the new input system?
so that I can detect any time you tap on the screen (other than an existing button)
@rich raft Local multiplayer is very possible now. https://forum.unity.com/threads/best-practices-getting-started-tutorials.875818/
I think its commercially viable for everything except Mobile.
InputSystem has zero support for Unity Remote which absolutely crippling to the mobile dev cycle (for a lot of folk, including myself)
It sounds like you're asking more about UI buttons than about the Input System
If you just want to detect touches in general, you can create InputActions bound to Touchscreen touches
@austere grotto that's exactly what i've done -- I have a pointer binding for my action. the problem is that it's triggered even if the touch occurs over a UI button
i've come up with this workaround:
private bool IsPointerOverUIObject()
{
var touchPosition = Touchscreen.current.position.ReadValue();
var eventData = new PointerEventData(EventSystem.current) {position = touchPosition};
var results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);
return results.Count > 0;
}
I've done similar stuff before
not sure if there's a better way to do it (I thought IsPointerOverGameObject would work but it doesn't seem to)
using IsPointerOverGameObject
interesting, did you get that working with touch input?
Do you have a Graphic Raycaster on your canvas?
No I've never done anything with touch but it should be the same
what's in the blocking mask? Maybe your buttons are not included?
it's set to "Everything"
although I'm not 100% on what blocking mask does right now, it's been a while
oh? looks like Mixed... from your screenshot
¯_(ツ)_/¯
yeah i think it always shows that
weird
clicking "everything" doesn't change it
did you call it like this? EventSystem.current.IsPointerOverGameObject()
oh what... suddenly it seems to be working again?
aha, i think this is a bug in unity. it only works with the input handling set to "both"
i had previously had it set to only use the new input system and it doesn't work set like that
which definitely seems like a bug
That will depend on your Input Module
Are you using the new Input System UI Input Module?
yep
And you have all the navigation actions set up on it? (this is done by default)
yes, and input works perfectly otherwise in the game
(with input handling set to "new" only)
ill try to make a minimal test project
yeah
you guys getting input drop when framerate drops with WasPressedThisFrame ?
i keep missing press on xbox controller in such condition and was wondering if it's a new input system bug
@full forge make sure you are checking in the correct Update or FixedUpdate
Update
InputSystem can be told to poll in Update or FixedUpdate in its preferences
ok, ur on PC for sure... XBone or X360 or?
PC
(the context window told me that :P)
will be on swith
meaning?
(your context popup looks like Windows)
sorry, I meant are you testing with XboxOne or a 360 controller?
it's a xb360 controller
have you looked at the Input Debugger window yet?
not yet, i just opened it
ok it just missed one input and the debugger showed the missing input
(hard to use that thing)
try setting your Application.targetFrameRate to something sane (ie: 60 or 120 or wha tnot)
ok yeah it's missing input but the debugger shows the input
also doe syour XB360 controller show up as an XBox Controller, Gamepad, or Joystick?
XInput, thats good
if you're on a 144hz monitor 144 is fine
Unity unclamped will run update at whateverframerate (ie: 3000fps on my laptop)
well the fps in stats in 112
it is fullscreen gameview
i haven't encountered dropped frames w/ XInput yet. can you tell me which InputSystem package version, Unity etc?
can't test tonight, but interested to replicate that one...
is there a way to filte only buttondown in that debugger?
it's unity 2020.1.17 with input 1.1.0 preview 3
Can you try 1.0.1 or .2?
there were problems with those, don't remember which though :/
quick question. how do I get the default hold duration from new input system in code? I'm already holding a ref for some inputSystem with hold interaction
I guess i'll have to create my own InputSettings asset and access it through an exposed serialized field 😐
why does this myAction.GetTimeoutCompletionPercentage() always return 1 or 0?
@cold silo that may defined per operating-system (ie: iOS may return a gradient 0-1, windows might return true or false)
oh I ended up ditching it.. its not reliable I'm using my own implementation now (just counting myself using unscaledDeltaTime and default hold time)
Any reason why my Camera Vector2 is always returning 0, 0 when I press WASD? If I replace it with the built-in Input Actions it works, but from the moment I swap to a custom set of actions, it stops working, despite them being setup exactly the same.
I ended up cloning the default asset and just changing it and it worked. Guess I'll never figure out the true reason. 🙃
Your input callback functions are hooked up improperly
Your functions don't accept the right parameter lists to be used as Input system callbacks
using new input system, how would i go about getting the input from only player 1 in a 2p game
im trying to do a char selection scene and i would like the first player to have input first before 2p can do smth
Im trying to submit code and it says Shows Compiler errror :error code show compiler error
I have a blank screen and it works
and I cnat submit anything that has no bugs since it blocks me
using.UnityEngine.SceneManagement;
this is the line of code that breaks most
PlayerInput FindFirstPairedToDevice(InputDevice device)
this helps a bit
@stark sinew PlayerInput and PlayerInputManager
last segment of my tutorials goes over it a bit
but TL;DR they want you to use PlayerInput, but there are other ways.
there is also a very nice Vikings demo from Unity team
Simple Demo is one of the demos that comes with the Input System. Works fine in Built-in renderer, but when I try it in URP, it's broken for some unfathomable reason. I think it had something to do with the extra code that comes on the URP camera, but I gave up anyway. I was trying to get up and running quickly for Wowie Jam, but I really should know better when it comes to Unity's packages.
I just went back to work on my main project.
It just kinda blew my mind. Unity continues to shock me with how atrocious their work is. There's absolutely no reason that a demo for the Input system should be dependent on the renderer you're using. PERIOD.
was it just not taking input at all? or was something else broken in the scene
I never fully figured it out. And I wasn't going to keep wasting my time. Like I said, there's extra functionality on the URP camera, and I think that might have been affecting it.
I'm not using the input system or the URP renderer for my main project, and I'm not a damn beta tester, so I just dipped.
Hi, everyone, I'm quite new to Unity and I'd like to ask about system design choice. So I have my input handled through the actions in the Input System, that's all working great. I'm also using processor to clamp my movement direction vector to length of 1 and I feel that it's great that the Input System is taking care of that even before it goes to my player script. Right now I need to rotate the direction relative to the camera and this got me thinking if I could also do this in the processor. Well I'm sure I could do that, but I am not sure if it's good decision. For example if I have more camera's in the scene and I will have to switch between them, can I somehow change the camera in the processor script? I will probably use Camera.main for now but I'm not sure if this is the right way to do it so I though I would make a property and if I ever need to change the camera I can just change the property there.
ok, so how do i fix that, it doesn't come from my code
and neither is in the PlayerInput
hello guys .. so i got a simple question . I made 2 scripts the first one handles the sprinting of the player and the second one handles the jumping .. so i made jumping and sprinting is only available when the player is grounded or on the ground only, the script of jumping and sprinting cannot work if only the player is grounded, so i made the player that he should press space to jump and its working but when i am sprinting which the player while he is sprinting is on the ground, when sprinting and pressing space he can't jump while he is sprinting but he can when he is not . i solved this problem by changing the key from space to something else and its now working but i want it actually to be space ... could someone tell me why this is happening and how to fix it ??
It may simply a hardware problem. Most generic keyboards have key membranes that limit the number of input from particular sections of the keyboard layout. You can learn more about it by Googling "membrane keyboard vs mechanical keyboard".
(it's also called "keyboard ghosting" or "rollover" https://en.wikipedia.org/wiki/Rollover_(key))
sometimes N-Key-Rollover
hello everyone, i receantly tried out the new input system in the unities own system. and i had some trouble with it on touch screens, all around gave me trouble and i couldnt understand it so i started using my old, crappy input manager. If anyone wants to give some ideas or discuss on it, i would love that
@west oracle thanks a lot
this New Input System is quite unstable, I'm considering switching to something more solid. Anyone here uses Rewired or InControl?
@full forge 😦 It is not unstable, its quirky.
I use InControl when I need things that InputSystem doesn't ofer
and I use Rewired when its in a project I didn't start.
they're both viable. InControl is my preference for XBox/PS stuff tho
losing binding is a bit more than quirky, let's call it not-fit-for-duty 😁
thanks for the feedback! why InControl your preference?
I've been using Rewired and I've been enjoying it. The developer is pretty responsive too. I haven't used InControl. I will probably continue to use Rewired for the next 2-3 projects, before even bothering with Unity's system again.
Unity doesn't have to even warn asset store creators when they make an official feature that's similar, anymore. The stuff they release is so bizarre, broken, and half-assed, all it does is drive more sales back to the asset dev.
InputSystem losing bindings? That sounds wrong somehow heh
I prefer the code-smell of InControl over Rewired
how would i change the prefab that the playerinputmanager is spawning but keep the playerinput
figured part of it out -
playerInputManager.playerPrefab = PrefabToSpawn;
now i have to figure out how to assign the old playerinput onto the new prefab
ope i can just destroy the old one and it works out
one more. How do i remove a player from the player input manahger
I'm having trouble with the mouse input
I don't see an option for the general mouse movement, the only movement related options I see are back and forward. How do I select the mouse delta as a value
or if mouse delta doesn't exist anymore, what is its replacement
wait
if I'm using PC and I don't intend for the game to be cross platform, do I still have to use the new input system?
why does everything break when i change something in visual studio and go back to the editor in playmode
i have to stop the game and hit play again for it to start working again
i get a null reference exception on every script that uses the input system
im using the input action asset
There's a setting...
Forget what it's called
But it makes it so unity recompiles and reloads your script during play mode. A side effect is any variable that is not serialized is lost
It's basically useless
You should find that setting and turn it off
Preferences - General - Script changes while playing
i am trying to make a program that will rumble an xbox controller when i hold down its a button but Unity says I have compiler errors. This is the code i currently have.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class Cube : MonoBehaviour
{
PlayerControls controls;
void Awake()
{
controls = new PlayerControls();
controls.Gameplay.Grow.performed += ctx => Grow();
}
void Grow()
{
gamepad.SetMotorSpeeds(1.000f, 1.000f);
}
void OnEnable()
{
controls.Gameplay.Enable();
}
void OnDisable()
{
controls.Gameplay.Disable();
}
}
What are the errors?
Oh probably in your awake
You're using parentheses when adding your listener
You don't use parentheses when adding a method to an event like that
so do i remove the parentheses from PlayerControls?
thanks
Hey Guys, I am trying to use the new Input-System with a 2D game. I would like to have an object to follow my mouse when my left click is pushed down and rotated when right is.
but since everything is not happening in the update method because I am using my inputaction method, I don't know how to "follow" the mouse in live.
which is the listener?
Sorry I think I was mistaken. Share your error message
there
Share the other errors
thats the error i get. only that one over and over
have you tested to make sure gamepad works on in general? as in other games on steam etc
Yes i have
Gamepad
try restarting unity as well to make sure its not a unity glitch? occasionally happens
gamepad.SetMotorSpeeds(1.000f, 1.000f);
Gamepad.current is probably what they're looking for
Gamepad.current is ment to be initiated upon detecting input froma gamepad tho
smeh, only if you care about multi-controller
their compiler errors are complaining about "gamepad" not existing
which...it doesnt 😛
cross the multi-device bridge when you get to the river
can somebody help me with the syntax of this
Vector2 mouseMovement = controls.Player.MD.ReadValue<Vector2>();
is this some sort of function arg with the <>
It's a generic type parameter/type argument
Hey Guys, for new input system how would you repeat an action triggered by an InputAction? Like I made an input action when my left click is held but the method OnHeld is running only one time. How can I make it repeat? in my case I would like to constantly get mouse position to move the object along with the mouse.
usually just set a bool to true in OnStarted, set it to false in OnCancelled. Then just use a coroutine or Update method to do something continuously in between
Or just start the coroutine in OnStarted and StopCoroutine in OnCancelled
mhh thanks for the answer. but what is onStarted? and on Oncancelled? I am just using the ON_nameofmyaction function.
private void OnMoveMirror() // click gauche est enfoncé
{
Debug.LogWarning("Souris enfoncee");
if (mirrorSelected & hitInfo.collider != null)
{
Vector3 mouse = Camera.main.ScreenToViewportPoint(Input.mousePosition);
Debug.Log("Position de la souris(viewPort) differente: " + mouse);
hitInfo.collider.gameObject.transform.position = mouse;
}
}
I'm curious, does it work if you add a parameter to your callback like this?
private void OnMoveMirror(InputAction.CallbackContext context) ?
If not you'll have to change things a bit
If adding that parameter works, then you can do a switch on the phase property of the context object
switch(context.phase) {
case InputActionPhase.started:
// Start holding
break;
case InputActionPhase.canceled:
// stop holding
break;
}```
ok let me try to add the parameter and this code
If not you'll need to set up separate listeners for each of the phases you're interested in
ok - but it works?
I'm not 100% sure this will work the way you're doing it. You're using PLayerInput right?
Ok. If this doesn't work I can help you change to a different way
(still using PlayerInput)
with an input action asset
right
the code is not working for the switch.
switch (context.phase)
{
case InputAction.phase.started:
Debug.Log("HOLD::::::");
break;
case InputActionPhase.canceled:
Debug.Log("releqsed::::::");
break;
}
the case is wrong.
those dont match each other
Sorry I had to mention 🙂 I am not a dev so even if I get what you are trying to do. :p
ok
not sure which one is which but they both need to be in the same correct form
the InputActionPhase.started send me "no def for started"
never,ind
nevermind
that was the capital letter
let's try again
"attempted to access a missing member"
never seen this error before.
It should definitely be like this:
public void OnMoveMirror(InputAction.CallbackContext context) {
switch (context.phase) {
case InputActionPhase.Started:
Debug.Log("HOLD::::::");
break;
case InputActionPhase.Canceled:
Debug.Log("Release::::::");
break;
}
}```
I just tested it
yes I have got it like yours now.
no, in my case the inputaction is holding the leftclick.
when I am doing so, I get the follozing
Ok I thought that might happen
so here's what we need to do
Then go to your PLayerInput
and change from "Send Messages" to "Unity Events"
Actually scratch the part with new methods
but make suire your existing one its public
which one?
onnce it's on Unity events, open the dropdown and find the action you care about
ok.
Make sure your code still looks like this: public void OnMoveMirror(InputAction.CallbackContext context)
ok
Let me know when your PLayerInput is set to "Invoke Unity Events"
ok so now there should be something called "events" on the PlayerInput
you have to expand it
yeah exactly
the event sorry
if you've ever worked with buttons in Unity, it's the same concept
how does that help to have a recurring execution?
we're getting there
ok.
you'll be able to separately read the start and canceled events
so you can do stuff in between
so what do I link to this event MoveMirror?
Your function
public void OnMoveMirror(InputAction.CallbackContext context)
you need to drag the object that has your script into the slot, and then pick that function from the dropdown
Object that has the script attached goes in blue circle
then you find your function on your script in the red circled dropdown list
yeah but I don't see my function there..
show screenshot?
yeah you've dragged the script into the blue circle
you need to drag the onbject from the hierarchy that has the script attached into it
it's probably the same object that PlayerInput is on
perfect
ok now run the game and try it
see if you get the logs for started and cancelled when you click and release
you mean the one from the switch?
yes
apparently its not detected because I have a debug log warning when entering the method and its not running either.
show the code?
🙂
now I get 2 time the debug.log once pressed and one time when released.
but not from the switch
we can do something like this:
bool isHolding = false;
public void OnMoveMirror(InputAction.CallbackContext context) {
switch (context.phase) {
case InputActionPhase.Started:
Debug.Log("HOLD::::::");
isHolding = true;
break;
case InputActionPhase.Canceled:
Debug.Log("Release::::::");
isHolding = false;
break;
}
}
void Update() {
if (isHolding) {
// Move your object to mouse position here
}
}```
oh should I map all the event to function when I go to Unity Events?
basically nothing is done automatically afterward?
Ah - yeah - you would need to do that >_>
It will break all your other mappings
maybe not worth it? T_T
oh great
but it's activated event if I am not HOLDING the button click
just a quick click is activating
anyways lets try the update method with the bool
Do you only want it to start after the user has held the button for a little bit first?
Or you want the dragging to start as soon as they press the button
the single click is supposed to be mapped to selecting a mirror
when selected, the user hold the click to start moving it.
is that the same click?
Or you click once to select
then click again to move
If it's the same click we can just change our switch a little bit:
switch (context.phase) {
case InputActionPhase.Started:
Debug.Log("Click start");
// select the object here
case InputActionPhase.Performed:
Debug.Log("HOLD::::::");
isHolding = true;
break;
case InputActionPhase.Canceled:
Debug.Log("Release::::::");
isHolding = false;
break;
}```
once to select, another one hold to move
yeah I wasn't sure how to handle it.
If you go to your input asset
and go to the action we're working oith
is it called Move Mirror?
that's right its called movemirror
If you go to the binding
you can add a processor
for holding
then try the modified code above
oh yeah
yeah its what I used
you're right
yeah ok
so try the modified code above
and see if it detects clicking, holding, and releasing properly
yeah exactly
alternatively
you could just leave SelectMirror as a separate action
and not handle it in this code at all
it can be bound to the same button
I moved the code out of the select and added to the started phase.
but my update code is bad I think.
because I am using a if a bool for something else.
its kind of working
but the mouse and the object are not in sync.
found (on google). it was due to the Z value not set to 0 of my ScreetoWorldPoint
@austere grotto Thanks a lot.
nice!
Glad you got it working
hopefully I didn't do too much damage to your project...
now I need to add a right click to the object. to rotate it.
how can we get the mouse move (right or left ) to become like an axis ? if I move left with the mouse I want negative value, right positive value. and use that to rotate an object?
Nevermind..
float deltaX = Mouse.current.delta.x.ReadValue();
here is the delta X value for the mouse.
you can do that. It's also possible to set it up as an axis in the input actions asset
When I press left shift and space at the same time, it sets the game on fullscreen, how do I stop that?
edit > shortcuts i think
I'm working with the Touch API, and on my Windows touch screen, it never seems to register something like a double tap
for (int iT = 0; iT < Input.touchCount; iT++)
{
Touch touch = Input.GetTouch(iT);
if (touch.phase == TouchPhase.Began)
{
if (touch.tapCount >= 2)
Debug.Log("Double tap");
else
Debug.Log("Tap");
Is there something I'm doing incorrectly?
I got to say, new input system is pretty rough around the edges considering it's 1.x.x
Just getting a human readable key feels like hacking and this code is not even in good state, several bugs and formatting issues like i.e "Space" vs "w/s/a/d" or "////" if all selected keys are e.g F1...F12
if (bindingIndex != -1) {
// issue: returns 2DVector, etc for composites, etc
displayString = InputControlPath.ToHumanReadableString(
action.bindings[bindingIndex].effectivePath,
InputControlPath.HumanReadableStringOptions.OmitDevice
);
// issue: returns empty string if e.g Esc, F1..F12, Enter, etc
string str = action.GetBindingDisplayString(bindingIndex, out deviceLayoutName, out controlPath, displayStringOptions);
if (displayString == "" || displayString == "2DVector") {
displayString = str;
}
}
Still, feels like a step to right direction
read a tut
Do you have any good suggestions? This code is from official rebind keys sample with few improvements
This doesn't cover rebinding or displaying human-readable key name in any form
public void OnJump(InputAction.CallbackContext ctx)
{
jumpButton = !ctx.canceled;
}```
so this code
gave me
this error and I don't get it
System.RuntimeType.InvokeMember (System.String name, System.Reflection.BindingFlags bindingFlags, System.Reflection.Binder binder, System.Object target, System.Object[] providedArgs, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, System.String[] namedParams) (at <9577ac7a62ef43179789031239ba8798>:0)
UnityEngine.SetupCoroutine.InvokeMember (System.Object behaviour, System.String name, System.Object variable) (at <2fae0a4cbcec42c9acc616494aa88f69>:0)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)```
Are you using "Send Messages" mode on PLayerInput?
yes
yes
SendMessages doesn't give you the InputAction.CallbackContext param
oh lol
then how does one do button actions 🤔
if you need the context, you have to use Invoke UnityEvents or Invoke C# events
C# events are my personal preference, if you're comfortable with them
ok thank you I'll look into that
Is there anyway to detect if a click is on the top bar of the application (the windows default bar with game Tite + fullscreen/close buttons)
Is there a way to change the layer of that top bar ? Or disable my input action while the mouse is over that top bar ?
It’s kinda built in top bar and don’t know how to get information about it
I may be mistaken but I think you will need to tap into some native windows calls to get information about that bar. Separate native calls for Mac
Humm i see... any idea how I can manage to block raycast behind that bar ? Because atm when I release my click my player teleport if the raycast succeed and not over ui .. since ui is on another layer... but I feel like I would need to create a new layer for my whole environment instead using default..
Hey, I'm trying to use the new input system with the invoke unity events behaviour, but methods I put under the events just don't run
For your information I managed to do it by using the scene resolution. The top bar isn’t consider in the scene resolution 🙂
in the send messages system; is there a way for me to tell when a message is no longer being sent. like an OffMove with my OnMove?
or in my actual case; OffJumpButton, OnJumpButton
The limitation with the SendMessage system was that you didn't get the context, right?
Do you really need to use the SendMessage version?
no but its the only way I know how to use the input system lol
should I do Invokes C# or Unity Events?
Either one is fine
ok so
how does one read a button as a bool in C#
with the input system
{
}
with this setup
So @pulsar lion
if that's using UnityEvents
you will get 3 calls to that function
every time the button is pressed
one for the started phase
one for the performed phase
and one for the canceled phase
you can see which phase it is from that context parameter
Personally I prefer to use C# events because you can individually subscribe to only the phases you are interested in. Only want to get performed events? Just subscribe to the performed event on the InputAction
I am pretty new to the input system and coding in general, I am using unity invoke events to set a bool to trigger things, the problem is I am trying to make a jab combo, so everytime attack is true, add 1 to the jabAmount, then if jabAmount = 2 play the follow up.
My problem is It is calling the event on button hold, so the moment you press the attack button calls multiple ones rapidly.
So I guess I am asking.
How do I call the invoke system once? I thought just setting the bool in the context.started would do it, but it seems to be looping through the entire method
{
if(context.started)
{
AttackInput = true;
}
if(context.performed)
{
AttackInput = false;
}
if(context.canceled)
{
AttackInput = false;
}
}
Of course it runs the entire method.
That's simply how code is executed in C#
it runs all the way to the end
I mean yea
what's not working about the way you have shown here?
If you use C# events you can subscribe specifically to whichever phase you want (started, cancelled, performed)
but they're a little more advanced coding-wise to set up
but the code you have here should work (it may not be the best way to do it, but it should work)
the expected result, you start the action, it sets the bool, and it doesnt loop back to context.started until you release the button.
what happens if I hold the button it constantly goes back to context.started, which doesn't make sense?
oh
just do this:
public void OnAttackInput(InputAction.CallbackContext context)
{
if(context.started)
{
AttackInput = true;
}
else if(context.canceled)
{
AttackInput = false;
}
}```
what's wrong about it
I had an issue using it that way for some reason for my autofiring script, you can use a seperate bool for the canceled part
You most likely have other code modifying that bool if it's not working right
Or I don't understand what you're trying to do
Its still firing context.started, when the expected behaviour it should only do it once if action is held right?
no
is the attack tied to a method or update function?
So you should get three calls when you press the button:
1 when you first start with phase == started
1 when you first start with phase == performed
1 when you let go with phase == canceled
if you're getting more calls than that
something else is up
I am trying to understand it in context of the old system.
Sorry for being bad
Lemme throw some debug statements in here and see if its firing once, or just my own logic
Logging would be a great idea:
Debug.Log("Called with phase: " + context.phase.ToString()); right at the start of the function
so I think its my logic, cause my hold debug is firing tons, but the start is only firing once
where is your "hold" debug? In Update?
its not anywhere I am only invoking the event in the player input
the object you attach
hold on
maybe not
Wait you're actually calling Invoke on the events from your PLayerInput?
or did I misread that
ok, so the event is being called here.
The event then sets a bool in my playerInputManager script. Then my state machine references the bool that gets set in my player input manager.
My debugging only gets called from that menu
ok alright, so I think I am getting whats happening
ok well I've only been helping you with the PlayerInputHandler part I guess?
im sorry for wasting your time, you have helped me understand a little bit more on the input system
my attackInput bool gets set to true, then never gets set to false, and so my state machine is constantly checking if my attackInput is true, its running way faster then I can press which is why its running like 12 times
it does on context.cancel, but the time it takes for me to press it and release is humanly to slow
so now im not real sure what I need to do
Thanks for the help again
not sure if this helps since I only had attacks tied to key press and not checked every frame but you can put a cooldown on the attack through code or animation event
then you can have a bool for attackPressedThisFrame and attackRequested
yea I am looking at it I think adding a timer would probably be the move
are you using triggers or int for your attacks in the animator?
ints
I'm confused at why your animation is "checking" the bool each frame?
Shouldn't you just set the bool once when you press the button
and unset it when you release?
yea im curious about that too, the reason why i switched to the new input system was that i dont need to call it eveyr frame
so not the animation system, I created a finite state machine
so in update its constantly setting an internal bool everyframe to the internal bool of the player input script
I hope that makes sense
You're using an event-based input system, why not set your bools in your FSM in an event-based way too?
because im not real sure how to set that up.
like before I would set the bools when we entered the new state, but then that gets called once, and it loses the listener for the button press
I think I figured it out, I have a new bug, but I understand whats causing it, I am going to go eat, so dont worry about responding, thanks for your help
It was massively helpful
Hey everyone, I have a custom controller and wondering if there is some way to get the axis values from it directly. It is a USB HID device and it shows up in Unity. The axis I want show up as "Slider" and "x-axis" in DIView. I don't want the user to have to configure the device.
I'm using the old Unity input system. Thanks
private void Awake()
{
playerInput = new PlayerActions();
playerInput.Movement.Jump.performed += ctx => jumpButton = true;
playerInput.Movement.Jump.canceled += ctx => jumpButton = false;
}```
can someone please tell me why I can't get this to work? just nothing happens when I press the jump button
using C# events
I think you need to enable your playerInput @pulsar lion
Something like playerInput.Enable()
hey my dudes, what should I use to detect VR input from all types of devices?
XR plugin doesn't work.
New input system doesn't work.
SteamVR works, but not for WMR.
Legit confused as hell here.
Anyone?
I am trying to utilize the new input system and cinemachine to create a manual 3rd person control system with manual camera movement from the right analog stick/mouse inputs. I cannot seem to find my way. I currently have an automatic camera following my player. Can anyone guide me in the correct path?
Have you tried Cinemachine Freelook?
There's ways to bind it to new input system now
That's how I utilized the automatic camera but I cant find the option to manually control.
Thank you
reading it now, thanks a ton!
@austere grotto ok so I have been utilizing the cinemachine inputProvider but there is still no option to manually move the camera around. Everything just follows. Is this something that must be hard coded?
You need to configure an input action to the provider
Like in that xy axis there
You'll need an inputaction configured to get your mouse input as a Vector2 of course
awesome, working on it now. Thank you @austere grotto
I have a class that implements IPointerClickHandler and IPointerDownHandler. The OnPointerDown method is called but the OnPointerClick method is not. Does anybody have any ideas as to why the latter is not being fired? I'm almost certain it has something to do with the fact that I'm using the new Input System.
OnPointerClick needs a full down and up sequence I believe
Are you doing that
When I'm clicking the Canvas item? Yes. I am clicking the Canvas item I click it down and up while over that item. And the Canvas does have a GraphicRaycaster.
WithCancelingThrough("<Keyboard>/escape")
will probably give you more of what you want
gamepads
or ignoring already bound buttons
also useful for flightsticks
ie "Ignore axis movement on anything that says Throttle"
My project currently uses a ScriptableObject with a series of commands that correspond to states, and uses Input.GetButtonDown to check if a button is pressed and starts the corresponding state
My code looks like this:
{
if (c.inputString != "")
{
if (Input.GetButtonDown(c.inputString))
{
StartState(c.state);
break;
}```
I'm completely lost on how to convert this to the new Input System though, would I rename the commands in GameEngine.coreData.commands to the names of my InputSystem Actions, and then check if those actions are performed?
TLDR I'm confused by the new InputSystem and how I would graft it onto my existing code, and I'm kind of overwhelmed by the complexity and weird syntax of the API
You could do that. That's certainly one way
inputActionMap[c.inputString].GetValue();
Maybe more directly translated as:
if (inputActionMap[c.inputString].phase == InputActionPhase.Started)
ah yea if @ancient berry wants "OnDown"
more realistically you want the extension
inputActionMap[c.inputString].WasPerformedThisFrame();
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.1/api/UnityEngine.InputSystem.InputAction.html#UnityEngine_InputSystem_InputAction_WasPerformedThisFrame (from 1.1 version only, not in non-preview form yet AFAIK)
The better thing to do probably is loop through all your actions and map them to your commands, and set up performed or started listeners, and stop doing this loop at all in Update
eh, debatable
we don't know their structure.
i often prefer in-line polling than registering/deregistering callbacks all the time
So, I'll be honest, I sort of have no idea what the functional difference is between these options
https://forum.unity.com/threads/best-practices-getting-started-tutorials.875818/ anyway 😛 these are a bit outdated and don't cover the 1.1 stuff.
I covered a lot of the "How to Input -> InputSystem for coders" stuff here
in particular Part #5 might be the most interesting to you
I appreciate these videos and I'll try to work through them and learn what I can, but I think I still don't get it
I'm using an Input Actions Asset, but everything I've seen seems to direct me to defining those actions in code(?) instead of through the editor
So like, I've gotten to this point
But I can't seem to get a consistent understanding of how to reference these in code
Does it have to be defined in an Awake function? How does it read inputs at all if it doesn't use Update/FixedUpdate?
Sorry if all of this is really basic stuff, this just makes zero intuitive sense to me as someone who's only worked with default Unity packages and methods
I'm just getting really confused and frustrated trying to go from the extremely simple GetButtonDown/GetAxisRaw that just returns a value, to this, with its own weird syntax and abstract nomenclature
Like I have no idea how or where it's getting things like context callbacks, or what those do
As far as I understand it, I have an Action Map inside the Input Actions Asset, and then I have a component that reads input
And at runtime, that component assigns functions to call when each of those actions is performed, through an Awake function?
So like, if I wanted to do chain attacks (pressing X four times goes State A→B→C→D) then would I define all of that behavior in the Awake function, or in an Update function?
Sorry if this is a huge wall of text, I'm just really wracking my brain here. This is sort of driving me crazy lol, I feel like I'm in over my head
The problem is
there are many ways of hooking these up to your code
So you may be reading various different sources that say various different things
A few ways it can be done:
- Check the "Generate Code" checkbox in the Input Actions Asset. This gives you a class that you can instantiate in your code (new MyControls()), and then you can subscribe to the input action callbacks (started, performed, cancelled).
- Use a PlayerInput component. This thing itself has 3 different modes: "SendMessages" which will call your methods named after the input actions. "Invoke Unity Events" which will give you a UI in the inspector similar to a UI button where you can hook up listeners that way. "Invoke C# events" which will let you hook up your listeners in code in an OnEnable() method or whatever
- Use a direct reference in your code to an InputActionAsset. WIth this you can use the various methods on the asset reference to get to the action maps, and again hook up listeners to the started, performed, or canceled events.
Also for most of these ways - if you get an InputAction reference, you can use a polling approach where you check the state of the action each frame, which will behave a bit more like the old input system @ancient berry
By the way if you're not familiar with UnityEvents or C# events, you will probably struggle with most of this
I don't have any experience with UnityEvents or C# events, but I...vaguely know what they are?
I would recommend devoting some time to getting familiar with them
they are used heavily in the new input system
ALternatively you can try to stick with a polling approach
basically you get the InputAction references and read the state of them during Update, as you would in the old input system
Could you give me a short explanation of what the difference is? Reading them through an Update function seems like it would be way more manageable
the difference is instead of checking them each frame in Update, the input system calls a function in your script when the button is pressed for example
So, is that more memory efficient or something?
Like, am I losing any functionality by using the polling method?
You won't lose functionality
In some circumstances, the event based way is less resource intensive
because you don't need to run any code each frame
In terms of making a single-player game that's not terribly graphically intensive, would you say it would make a noticeable impact?
Again it depends
The game currently runs at like 1000fps on outdated hardware but trying to figure this out is inflicting Psychic Damage on me, so I might honestly be okay taking a performance hit if it means my game returns to a playable state
Like let's say you have 100 objects in the scene and they all do something depending on different keys you press on your keyboard. Rather than all of them running an Update function every frame that checks the state of your input, if they all just subscribe to events, you can see some big performance improvements from not having to run Update() on each one of them
Honestly, I woulkdn't worry about it
Do whatever makes sense to you
if you run into a performance issue later, you can make changes then
The only object that's intended to respond to player input will be the player object
And I guess UI
I guess I'm wondering, if this is so much of a struggle, why not stick with the old system?
My main motivation(s) behind wanting to switch are the ability to rebind controls at runtime, and being able to use generic code that isn't redundant
Currently the keyboard controls use the numpad for dodging, but on controller it uses the dpad, so it's a GetButtonDown call for the numpad but it would be a GetAxisRaw call for the dpad because it's classified as two axes
gotcha
That, and my code has become extremely bloated and disorganized because walking forward/back and left/right use two independent axes instead of a 2D composite
And I guess I could just make my own Vector2 in code that takes the GetAxisRaw values of both axes, but the big thing is trying to assign both a button and an axis value to the same action
So right now, for the sake of testing, I've been running my input through a Steam Big Picture controller config that just rebinds the dpad to the corresponding numpad keys, which is not only pretty hacky but it makes it a huge cluster||heck|| to send to playtesters
Because I also have to send them the controller config and stuff, and just kind of pray that it works for them
Versus the plug-and-play nature of the new system (once it's actually working lol)
Thank you very, VERY much for talking me through this btw. I've been sitting at my computer with a concerned/confused wince on my face, getting sweatier and sweatier for like 3 hours at this point
And that's after listening to/watching 3 or 4 half-hour tutorials lol
How do I stop a ScreenPointToRay physics raycast going through UI elements? From googling around it seems like there's not much built-in way of doing this easily, despite it being something I'd expect being a pretty common problem?
The only potential solution I've found is to call EventSystem.current.IsPointerOverGameObject() before doing the raycast to determine if the cursor is over a UI element - but this doesn't work for me, presumably because I'm using the new input system
I could just deactivate my targeting system when things like the ESC menu are opened, but that wouldn't stop rays being cast through HUD elements etc. So a custom solution would require a lot of checks - surely there's an easier way?
Physics.Raycast will never hit UI elements because they do not have Colliders.
With proper use of Unity's Event system you can achieve what you want
I did this in my current project with the new Input system: @acoustic holly
mouseY -= Input.GetAxis("Mouse Y") * verSensitivity;
mouseY = Mathf.Clamp(mouseY, -30, 60);
r = Quaternion.Euler(mouseY, mouseX, 0f);
camOffset = Vector3.back * cameraDistance;
camOffset = r * camOffset;
transform.position = player.position + camOffset;
transform.rotation = r;``` Is it a good idea to put my control camera code in the update method?
I think the question is which update method? Is this the update method of some other Script? Or is it a dedicated camera follow Script
it's in the Update() method of the camera follow script
That's fine, but usually camera follow happens in LateUpdate to make sure the thing you're following has moved first
Oh yeah that makes sense I'll switch to that thanks
so I have this code:
_actions.Camera.Movement.performed += ctx =>
{
and Movement is a Vector 2 for WASD and the Arrow keys
when i press and hold it though it does not re-do this every frame
only once i press, release and press again
is there any way to do it while the key is held down?
I have done a refactor so it uses the Update method but i still would like to know how i would do it using callbacks
Hello !
I'm trying to make a simple vr game for a school project
I'm on quest
however after installing xr interaction toolkit and everything that is needed
when I hit play, I only see a fixed view and nothing's moving
I'm using the new XR action-based input
can anyone help me ?
thanks !
Okay, input system.
Lemme just copy what i had from general.
Here's my action map.
https://puu.sh/HoHDF/529c1489f8.png Here it is in action.
https://puu.sh/HoHo6/2c2017c7e0.png Here's what I want -- the ability to select two players with any two devices.
(Imagine the arrow on player 2. I was too lazy to go back into my title screen, sorry.)
Does anyone know how I could do this with the new input system? And not with prefabs?
@austere grotto What is a basic script I can put in my update method to utilize mouse/delta and a right analog look movement with most basic 3rd person controllers? I cant seem to get anything going.
@austere grotto Finally figured it out, there is a bug in the latest version. Downgraded 2.6.3 and it worked fine.
I have a collision with an enemy that sets a bool to 'dead'.
I want player input to stop working when he is dead.
Should I check "if dead" before player input, and prevent input from being read? And if so, how? (option 1)
Or should I just let the player press keys and read input, and check if he's dead in every move/jump/run/crouch function, and then have it do nothing? (option 2)
option 1 seems like it would be less code and easier to update, but i'm not sure if i can unsubscribe from events
If you use events you will only get changes. If you want this data every frame either change to polling each frame or save the value from the event in a variable. Additionally you'll want to subscribe to the canceled event as well to detect releasing the control.
Disable the action map when the player dies, or disable the player movement component (e.g. your script)
Thanks! Makes sense! If i just disable the action map, I can probably sack the bool, too...
How can you use the back button on mobile? I tried Usages->Back, Usages->Cancel and the Escape key but none of them work
I'm working with the new input system, I want to click on an object and using boiler plate raycast to interact with the object. But every time I use this it calls "OnInteract" 3 times. I'm assuming because there are 3 call backs to the unity event associated with clicking the mouseclick. How do I get it to stop? I'm assuming I need to read the callbackcontext but the documentation here is extremely vague as to what type I need to actually check
///In the editor I have a PlayerInput component with "left mouse button" generating a unity event for OnInteractMouseButtonPressed()
public void OnInteractMouseButtonPressed()
{
var target = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
RaycastHit2D hitData = Physics2D.Raycast(new Vector2(target.x, target.y), Vector2.zero, 0);
var interactable = hitData.transform.gameObject.GetComponent<IInteractable>();
if (interactable != null && interactable.interactRange > (this.transform.position - hitData.transform.position).magnitude)
{
interactable.OnInteraction();
}
}
@plucky flint Are you using SendMessage to deliver your input events?
No, I'm using the "Invoke Unity Events" option as that seemed easier but I may be wrong
Try public void OnInteractMouseButtonPressed(InputAction.CallbackContext context)
There are several stages to actions, like when it starts, continues, ends etc.
Yeah, there are those 3 which is why I assumed that was the issue. But if I include the context, I don't even get this Debug.Log message
public void OnInteractMouseButtonPressed(InputAction.CallbackContext context)
{
Debug.Log("MouseButtonPressed");
Is it still hooked in the inspector?
yes. the only thing I change is the InputAction.CallbackContext context addition
wait, it changes to missing
The inspector value? Yea likely since the signature was changed
Okay, so that was fixed. I'm still getting Debug.Log("MouseButtonPressed") three times
How would I filter the context for just the initial mousedown condition? Thats what I'm missing
You can do a switch statement based on the phase of the callback context.
switch (context.phase) {
case InputActionPhase.Started:
// blah
//etc...
}```
these are the possible values
started, performed, canceled are the main ones
IDE should auto complete it for you
Ah, so the phase.
I was looking for context.action.name
something along that lines
Personally I prefer using C# events, so you can optionally subscribe to all, some, or none of those phases.
but either way works
I was about to just move to the SendMessage command, but I would have the same problem.
Yea I asked about SendMessage because you don't get the context
might be simpler if you only care about the performed phase though
Ah, well that's helpful thank you. How would you go about subscribing to a specific phase of a c# event?
Once you have a reference to the InputAction, you can subscribe to it like any normal C# event
e.g...
void OnEnable() {
fireInputAction.performed += HandleFirePeformed;
}
void OnDisable() {
fireInputAction.performed -= HandleFirePeformed;
}
void HandleFirePerformed(InputAction.CallbackContext context) {
Debug.Log("Fire!");
}
I put OnEnable and OnDisable because it's a good way to make sure you clean up your listeners
You can get the InputAction reference either from a PlayerInput, directly from an InputActionAsset, or from a generated InputActionAsset class.
If you have a PlayerInput, you might find the InputAction like:
fireInputAction = myPlayerInput.actions.FindAction("Combat/Fire");
Where "Combat" is the name of the action map and "Fire" is the name of the action
awesome! thanks for the detailed write up
Hey so I am using the Input system namespace but anytime I am trying to get PlayerInput index it returns with the no valid property error what could I be doin wrong?
So... I hate Unity's InputSystem.... But I Like Unity's EventSystem and UiElements.... But I dont like unity's input system.
show the code && error message?
Is there any way to use the input system I created and integrate it with EventSystem?
like, even a place to start?
Yes you just need to write your own Input Module
The old input system used the Standalone Input Module
new system uses InputSystem UI Input Modulke
you just need to write your own Input Module for your input system
that's the link between the input system and the event system of the UI
..... is there is any like... documentation to help me along that way?
ok ok thank you.
private int playerIndex;
private void Awake()
{
playerIndex = this.gameObject.GetComponent<PlayerInput>().playerIndex;
}
Awake() needs to be capitalized. Aside from that you are getting some error?
Error CS1061 'PlayerInput' does not contain a definition for 'playerIndex' and no accessible extension method 'playerIndex' accepting a first argument of type 'PlayerInput' could be found (are you missing a using directive or
Did you name your class "PlayerInput"?
ofh
If you're not sure what I mean by that - can you share all your code? (I don't see class declaration for example in what you shared)
I have some old scripts from my prototyping phse named PlayerInput
I also could write my own UiSystem... which while not efficient would be fun....
hmmmm
@austere grotto I wasnt entirely honest when asking this question, I allready knew EventSystem uses InputModules and that I needed to create my own, but I couldnt seem to find the documents i needed to make my own so I gave up. Thank you for sending me that manual though, I had not been to the manual site before.
it's pretty essential for doing anything in Unity IMO
For people who are experienced with the new input system, do you find that the PlayerInput/PlayerInputManager wrapper classes are useful outside of local multiplayer?
ah ok, yeah I was having a similar experience (I prefer to use the generated C# class) but wasn't sure if I was missing something by dropping it
The main benefit is multiplayer related, as you observed
or quick setup with Send Messages mode, but that mode is quite deficient since you can only listen for performed events with that
yeah that's been the thing really, I kept adapting my various code paths to it to get around the limitations. Ultimately though, I don't think it's useful for my purposes. Thanks for the insight!
hello me again, I am using the player input manager to add more players, how do I get the index of my newly addeed players? Can I do this from the player input manager?
PlayerInput has a playerIndex on it
when your manager spawns the prefab with the PlayerInput you can read it from there
So right now I am not spawning from script. I am just letting the player manager do it, since I am just trying to wrap my head around it.
hey guys, when i select a button in script, it doesn't highlight in the UI. everything else is fine, how do i fix that?
this is general navigation stuff, so just going through buttons in a menu, the selecting when i go through it works, but the button when i call .select() doesn't highlight, navigating to the next buttons will highlight tho.
I could need help with the input system, all my controls are working except my Ability for slowmotion. When I press the button on my Controller the method in my script isn't being called idk why
I have my cursor lock state set to locked and a action that gets <Mouse>/scroll
here is the code i use with it
but when its locked this event never runs
how can i fix that?
(if the cursor is not locked the event runs just fine)
Y'all know how to make a scrollbar that's affected by gamepad input?
Input system really doesn't play nicely with locked cursor at all
I'm struggling with that in my project too
New one
And sorry, got distracted after trying to use a few different codes I've found online, none work so far .-.
u using code or asset for editing the input scheme
Using asset atm, but am willing to use anything that works
Think I may have described it wrong though
What I need is a scrollbar that automatically scrolls to the Eventsystem.current.currentSelectedObject
wat
how do you make the keybaord work
send a screenshot of your setup
Right now it just gets the default UI input from the Eventsystem
The eventsystem itself works perfectly, it selects the objects in my dropdown just fine. But the actual window doesn't scroll down to the object selected.
It's just selected out of view
Does anyone know how to fix this
I googled people said add that "Cancel" input but it's already there
nvm fixed it
@hoary heron https://gist.github.com/marcelschmidt1337/14a1528f98307d3d826f522196e9817f Looking for something very similar to this. This works mostly, but it doesn't show the last option