#🖱️┃input-system

1 messages · Page 29 of 1

austere grotto
#

You can also add [DefaultExecutionOrder(-1000)] to the InputSystem class which would force its Awake/OnEnable to to run before that of other scripts

#

which might make things a little easier to work with

junior wraith
#

would you recommend it for every manager in the scene?

austere grotto
#

no

junior wraith
#

fair enough

#

thank you man, helped me i lot ❤️

steady geyser
#

@austere grottoThank you, however how do I rebind say, the Left binding for Move/Primary/Left?

#

how do I access that specific binding?

steady geyser
narrow vector
#

Apologies if there's a better place to ask this: How do I move my camera in the scene editor as I tweak things without it feeling so chaotic? I feel like I spend more time correcting my position in the editor than I do actually doing the things I want and wanted to see if there were tips!

distant sphinx
#
GitHub

DualShock 4 gyroscope extension for Unity Input System - keijiro/GyroInputTest

最近の FPS, TPS はゲームパッドのジャイロ入力に対応していることがありますよね。これを Unity の Input System を使って実装するにはどうしたらいいんだろう……と思ったので、試しに作ってみました! ジャイロ入力を作ってみたい!と思っていた方はぜひ参考...

▶ Play video
#

Unity Japan has a video about it and a example

#

I have implemented Nintendo Switch Pro Controller Gyro with this layout override

        //https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/imu_sensor_notes.md
        //According to that, accelerometers start at 13, and gyro at 19, but from debugging the data that seems switched around?
        public const string SwitchProControllerGyro = @"{
          ""name"": ""SwitchProControllerHIDSensor"",
          ""extend"": ""SwitchProControllerHID"",
          ""controls"": [
            {
            ""name"":""accelerometer"", ""displayName"": ""Accelerometer"", ""format"":""VC3S"", ""offset"":19,
            ""layout"":""Vector3"", ""processors"":""ScaleVector3(x=-1,y=-1,z=1)"",
            ""noisy"": true
            },
            {""name"":""accelerometer/x"", ""format"":""SHRT"", ""offset"":0 },
            {""name"":""accelerometer/y"", ""format"":""SHRT"", ""offset"":2 },
            {""name"":""accelerometer/z"", ""format"":""SHRT"", ""offset"":4 },
            {
            ""name"":""gyroscope"", ""displayName"": ""Gyroscope"", ""shortDisplayName"": ""Gyro"", ""format"":""VC3S"", ""offset"":13,
            ""layout"":""Vector3"", ""processors"":""ScaleVector3(x=-1,y=-1,z=1)"",
            ""noisy"": true
            },
            {""name"":""gyroscope/x"", ""format"":""SHRT"", ""offset"":0 },
            {""name"":""gyroscope/y"", ""format"":""SHRT"", ""offset"":2 },
            {""name"":""gyroscope/z"", ""format"":""SHRT"", ""offset"":4 }
          ]}";

Gets registered with ```cs
InputSystem.RegisterLayoutOverride(SwitchProControllerHID_Sensor.SwitchProControllerGyro);

#

Then I just implemented it directly in a Inputs Action Asset

#

You do need to figure out the memory layout of the data and the format, you can do that with the Input Debugger

#

If you are using Windows then maybe its fine...?

#

I tried connecting one of my wii motes to my linux pc and it just didn't work

#

If the wiimote works out of the box and is just missing gyro you can use an override, just re-read your message and this quite isn't "own custom device layout" from scratch

#

but the principles of json is kinda there..? The manual has a section on custom devices

#

its complicated

#

A lot of this is debugging the device and knowing your way across the hardware

#

I'd check github if I were you, additionally check the SDL2 repository since they just implement every controller in existence

clever pilot
#

might switch over to vr if i cant make it work :/

#

ill look into those links tho, ty!!

steel remnant
#

I'm making a 2D board game, I need to interect with both the UI, and the Grid when the user click outside the UI. I'm starting to learn about UI Toolkit and the new Input System. I'm having hard time understanding what is up to date. I see a lot of tutorials about the new Input System with ImGUI. Is UI Toolkit intended to work with the Input System, or on its own ?

austere grotto
#

but UIToolkit has its own event system and I'm not sure how that works

steel remnant
#

Okay well I wasn't sure which channels it would more fit. But thanks for the anwser

grim dock
austere grotto
#

the confusing thing is that you have BOTH the PlayerInput component here

#

AND you have InputActionReferences

#

I have just showed you how to use InputAcitonReference

#

with this way you would get rid of your PlayerInput component

#

You should not be trying to use both

#

they are two different approaches entirely

#

If you wish to use PlayerInput with SendMessages as you have, you would instead do this:

Vector2 moveInput;

private void OnMove(InputValue iv)
{
        
  moveInput = iv.ReadValue<Vector2>();
}

void Update() {
  // move your character with moveInput here
}```
#

Pick one or the other

#

not both

grim dock
#

So I don't need the player input component?

austere grotto
#

Read what I said

#

pick one

#

PlayerInput or InputActionReferences

#

not both

grim dock
#

I'll just use the inputactionreferences then

grim dock
austere grotto
#

OnMove would only be if you are using PlayerInput

#

I already answered this above

grim dock
#

So those are for when your using Player Input ↑

austere grotto
#

Specifically PlayerInput in SendMessages mode

grim dock
grim dock
grim dock
#

I made some changes and I'm getting errors in handle movement should I store current Input as a variable? private Vector2 currentInput;

austere grotto
#

you can't use a local variable you declared in one method in another method

#

yes you need a member variable here

real coral
#

The issue I'm currently having is when I play my game, I can't click on any of the buttons. It's like pressing on the buttons doesn't do anything.

Important information:
I am using Version Unity 6 (6000.029f1).
I have both input systems enabled
All the buttons have the same IMG & TXT (just different names & images)

real vine
#

How come the text isn’t appearing on the screen? I used input mouse position and camera.main.screentoworldpoint of the mouse position and set the text box position to the screen to world point of the mouse position

timid dagger
austere grotto
austere grotto
#

You're putting the text outside of the screen

real coral
austere grotto
#

a canvas is a container inside which you are meant to place a lot of ui elements

#

you just need one canvas at the top level

#

not sure what tutorial you were watching

#

either he had some special reason for that or it was just wrong

real coral
#

Ah okay I'll give that a shot later on today, thankyou for your help

verbal remnant
granite galleon
#

its hard to tell but does anyone know why my mouse is jumping around? ill slightly look around and ill just start jumping and stuttering around. my friend said it was a unity engine issue but im not sure

real coral
#

This is the set up, I have removed the canvas on each panel except the Journal_Book (Question would the "root" of the prefab have to have a Canvas instead of the first). I have added the first 2 buttons, (as once I get them working I can just impliment the same thing to the rest.) & also added the code is down below, anything I try & do it doesn't wanna work.


public class JournalCode : MonoBehaviour
{
    [Header("UI References")]
    public GameObject Journal;
    public GameObject[] pages;
    public int defaultPage = 0;

    private bool isJournalOpen;
    private int currentPageIndex;

    void Start()
    {
        foreach (GameObject page in pages)
        {
            if (page != null) page.SetActive(false);
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.J))
        {
            ToggleJournal();
        }
    }

    public void ToggleJournal()
    {
        isJournalOpen = !isJournalOpen;
        Journal.SetActive(isJournalOpen);

        if (isJournalOpen)
        {
            ShowPage(currentPageIndex);
            SetCursorState(false); // Unlock cursor when journal is open
        }
    }

    public void ShowPage(int pageIndex)
    {
        if (pageIndex < 0 || pageIndex >= pages.Length) return;

        // Hide current page
        if (currentPageIndex >= 0 && currentPageIndex < pages.Length && pages[currentPageIndex] != null)
        {
            pages[currentPageIndex].SetActive(false);
        }

        // Show new page
        pages[pageIndex].SetActive(true);
        currentPageIndex = pageIndex;
    }

    // Call this from other UI scripts (e.g., Host screen)
    public void SetCursorState(bool shouldLock)
    {
        Cursor.lockState = shouldLock ? CursorLockMode.Locked : CursorLockMode.None;
        Cursor.visible = !shouldLock;
    }

    // Debug method
    public void DebugLog(string message) => Debug.Log(message);
}```
tame oracle
#

I really need help I don't why my swipe detection is not work, it's just not give me the swipe end position and it's been over a week since I start trying to add swipe mechanic.

tame oracle
#

and I did try to subscribe the Onjump and OnJumpPosition to different input phases and didn't work either

wicked sable
#

looks like i.m not the only one who faces issuses with input system

austere grotto
dire kayak
#

I want to track the active input device (i.e. the input device that's currently used).
I tried to listen to the onControlsChanged event and call this function:

private void OnControlsChanged(PlayerInput input) {
    if (input.currentControlScheme == "Gamepad") {
        CurrentDevice = DeviceType.Xbox;
    } else if (input.currentControlScheme == "Keyboard&Mouse") {
        CurrentDevice = DeviceType.KeyboardMouse;
    }
}

But there seems to be an issue: Even when only using a controller, the Keyboard&Mouse branch gets also called. In the editor, when clicking OUTSIDE the game view, it works (that it only tracks controller) . but i dont want to click outside of course (in the build it wouldnt work because of lost focus)

Anyone know how to fix that?

dire kayak
#

I can't find a way to fix this

dire kayak
#

I tried all the different supposed "solutions" but its always the same - if i dont manually click outside the gameview it triggers a keyboard and mouse input even if i only press buttons on the controller

tame oracle
#

When i click outside the gameview it trigger and it gives me the swipe end position

#

Is this issue with the unity engine him self?

dire kayak
#

I can't tell. But I've tried the whole day, all possible solutions i can find on the web result in the same issue

tame oracle
#

Is there someone talk about this issue in internet?

#

Like YouTube??

dire kayak
#

not specifically. which makes me wonder because it is such a basic thing everyone would want in their game

dire kayak
#

let me ask it differently, is someone using onControlsChanged to track the current control scheme - and if yes, which version of InputSystem because then i'll try to downgrade

dire kayak
#

I even downloaded the official sample from the InputSystem In-Game hints. it has the same issue, it flickers between the keyboard and controller hints. (except you click outside the in game view)

tame oracle
#

I'm done with unity I'm switching to godot

#

I'm so done with it

#

I spent the whole day trying to figure out why I can't get swipe end position when I the touch cancel

#

But it doesn't work no matter what I do

#

And it gives me the swipe end position when i click the outside the scene

austere grotto
#

Also it's kinda recommended to just use EnhancedTouchSupport directly for touch gesture stuff

#

rather than input actions

#

it's possible with input actions but awkward

#

For doing it with two actions I would basically expect:

  • 1 action for the touch/release
  • 1 action for the touch position

and you would just read the position action's current value with ReadValue inside the touch/release action callback directly

#

Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();
It's odd you're doing this and ignoring the callback context^

dire kayak
tame oracle
dire kayak
tame oracle
tame oracle
#

and I did have this same problem too before year ago when I was trying to get the space release button

tame oracle
# austere grotto Also it's kinda recommended to just use EnhancedTouchSupport directly for touch ...

Then tell me why in this too videos they do the same thing i did and it work with them but not with me?? https://youtu.be/XUx_QlJpd0M?si=w_Ei3X231Nnrd4Qe

Detect swipes and it's direction with the new input system in Unity 2020. I also show how to add a trail renderer for a cool swipe effect.

ᐅGet the full Source Code Bundle to my Unity Tutorials 🤓
https://sam-yam.itch.io/samyam-full-source-code-to-all-videos

📥 Get the Source Code 📥
https://www.patreon.com/posts/45726030

🔗 Relev...

▶ Play video
dire kayak
#

lmao i just booted up my pc after the horrors yesterday and suddenly it works. 😂 wtf

dire kayak
#

yes the flickering is just gone suddenly, i didnt change anything since yesterday

#

guess rebooting did the trick for me, restarting unity did not

tame oracle
#

well good for you

#

Me I will continue to....

#

I don't really know

#

what should i do

dire kayak
#

i never tried to make a mobile game, i dont know anything about touch input :/
i think i'm not able to help here

tame oracle
#

I will probably switch to mobile engine

#

But I don't understand how I the only one how face this issue too times in the row?

#

And how there is none talk about it???

dire kayak
#

i know it's frustrating when you're stuck and it seems like it just won't work. maybe take a few days off and look at it when you're refreshed - it helped me in the past and it keeps you sane

tame oracle
#

thanks for the advice

dire kayak
#

if you could set up a minimal example of the issue and invite me to the github repo i also could take a look at it

austere grotto
#

They did it more similarly to how I described above

tame oracle
tame oracle
#

the different is I change the way the logic is place and how it work

#

it doesn't explain why i get the end position of the touch when i press out of game scene

#

I did the same in the video

#

like same same

#

and it work

#

but my code still does not work

austere grotto
tame oracle
#

Sorry guys

tawdry tundra
#

Hey this might sound really weird but obviously when you press a button you can either use space bar or click with the mouse, is there a way to remove the ability to press with space bar and either just keep it as left click or change to another key ? Thankyou

distant sphinx
#

If I want to make a Virtual Mouse, because I want to unify both console and actual real mouse I/O for content like UI or gameplay-wise like shooting, but I don't think I want any of the additional content there is in VirtualMouseInput such as graphics or the actions there are, should I just create a Mouse myself and update its position manually?

#

Rather confused on how to approach this

#

Nevermind I suppose...? You can't have Virtual Mouses and use UI Toolkit?

simple scarab
#

And if so then you could add a canvas just for the virtual mouse, or you can write your own wrapper that does the same as the virtual mouse to simulate a mouse and use your own display method for it

simple scarab
#

Is there a way to activate the stacktrace for input? Like, when doing Debug.Log it currently hides stuff in the input and inputsystem namespace from the stacktrace
edit: Ended up just generating my own stacktrace and printing that

spring herald
#

Has anyone had trouble with getting PlayerInputManager to notice its JoinAction rebinding to a new button? I'm not sure if I'm rebinding wrong or it's a bug with PlayerInputManager.

Boiled down my rebind script to as little as I could. Also attached a *.zip of me isolating the issue in a unity scene in my failed attempt to figure out what's going wrong.

public class IsolateRebindBugRebinder : MonoBehaviour
{
    [Tooltip("Key to press to initiate an interactive rebind for the join key.")]
    [SerializeField]
    private InputAction rebindJoinKey = new InputAction("rebindJoin", binding: "<Keyboard>/r");

    [Tooltip("InputAction to be perform rebinding on.")]
    [SerializeField]
    private InputActionReference join;

    private InputActionRebindingExtensions.RebindingOperation rebindOperation;

    void OnEnable()
    {
        rebindJoinKey.performed += RebindJoinKey_performed;
        rebindJoinKey.Enable();
    }

    private void OnDisable()
    {
        rebindJoinKey.Disable();
        rebindJoinKey.performed -= RebindJoinKey_performed;
        flagRebindOpForGarbageCollection();
    }

    private void RebindJoinKey_performed(InputAction.CallbackContext obj)
    {
        join.action.Disable();
        rebindOperation = join.action.PerformInteractiveRebinding()
            .OnComplete(onRebindCompleted)
            .Start();
        Debug.Log("You pressed the rebind key " + rebindJoinKey.GetBindingDisplayString()
            + ". Press the new key you'd like to use for the join action.");
    }

    private void onRebindCompleted(InputActionRebindingExtensions.RebindingOperation operation)
    {
        join.action.Enable();
        Debug.Log("join key was rebound to " + join.action.GetBindingDisplayString());
        flagRebindOpForGarbageCollection();
    }

    private void flagRebindOpForGarbageCollection()
    {
        rebindOperation?.Dispose();
        rebindOperation = null;
    }
}
austere grotto
#

So really the issue here is that you have your own separate reference to the input action. You should rebind the one from the PlayerInputManager component directly.

spring herald
# austere grotto So really the issue here is that you have your own separate reference to the inp...

Thanks for finding that bit of doc I missed! It worked by adding a reference to PlayerInputManager's JoinAction in my onRebindCompleted()!

private void onRebindCompleted(InputActionRebindingExtensions.RebindingOperation operation)
{
    join.action.Enable();
    PlayerInputManager.instance.joinAction.action.ApplyBindingOverride(0, join.action.bindings[0]);
    ...
}

Now I just need to look into a way to get the bindingIndex from join.action instead of hard coding 0's.

magic rose
#

Can anyone help me
key binds dont work anymore in my unity game after restarting

spring herald
# magic rose Can anyone help me key binds dont work anymore in my unity game after restartin...

That's too vague to diagnosis. Issue could be that:

  1. The device linked to those key binds is no longer connected to your computer.
  2. After you've verified your computer accepts the device functions, verify Unity's InputDebugger sees it.
  3. After that, set a breakpoint in the code that responds to the keybinds to see if your code is at fault.
  4. If the breakpoints aren't hit, try making a new Unity project to see if the key binds can be hit in a fresh project.
  5. After you can get them hit in a fresh project, figure out the diff between that fresh project and your old one.
spring herald
hollow quartz
#

why i cant drag anything here?

austere grotto
#

Your objects are probably TMP_InputField

#

So you should make your fields TMP_InputField

hollow quartz
oak steeple
#

Hello, I am trying to get the Input System Package working with a scroll wheel input and I am having quite a bit of trouble.

I would like to create a "zoom" function where my mouse scroll wheel is the user input. Scrolling up should zoom in, scrolling down should zoom out.

I have configured my input system action for Zoom to use a 1D Axis (since I cannot find any alternative). This gives me a Negative and Positive input, I have bound these to Scroll/X and Scroll/Y respectively. The issue is that no matter what I do, the result of these inputs is always identical. I currnetly have this in my code to read the value:

InputAction zoomAction = InputSystem.actions.FindAction("Zoom");
float zoomValue = zoomAction.ReadValue<float>(); 

Right now, zoomValue is always 1 regardless or when way I scroll my mouse wheel. How can I get the proper axis value so that I can distinguish which way the user scrolled? I.e I would expect the values -1 and 1 so that I can multiply this by a zoomFactor to control camera zoom.

I have tried inverting the input value with a processor, but this seems to be ignored for the 1DAxis values

oak steeple
#

Small update on this, after some playing, I set the parent Zoom to be an axis input and I now get negatives and positives, but I can see that Debug.Log is logging 0 as my zoomValue, missing about 99% of my mouse scrolls. If I scroll REALLY fast (by unlocking my scroll wheel and letting it rip), I can get about 50% of frames reading an input.

This is running in Update and it is logging the 0 value for every frame, so it is not that the update is missing the update, seems like maybe the value is being floored? Or otherwise cast to an int? I cannot find any setting for this. shrug

oak steeple
#

Thanks to monkey with a typewriter theorem, I got it working. Wish the docs for this were newer than 2021 😔

#

Hard to call this the "new" input system when the docs are 4 years out of date.

austere grotto
#

which is not the usual thing you think of for mouse scroll

#

Scroll Y would be usually what you want

#

having them both bound to the axis is quite weird.

#

YOu certainly wouldn't use a composite binding for this

oak steeple
# austere grotto YOu certainly wouldn't use a composite binding for this

I now have set this to Scroll/Down and Scroll/Up, though because this is called an axis, I would expect it to allow for a single axis as the input and to give me the negative/postive value of the axis. Using Scroll/Y seems to be invalid as an axis here as it only corresponds to an up movement on the mouse wheel scroll.

austere grotto
#

There's no reason to use a composite

#

Your problem is you made the binding itself a composite binding

oak steeple
oak steeple
austere grotto
#

opening Unity right now to show you

#

this works

#

One thing you need to do is make sure you actually have the game window focused as you scroll though

#

it won't pick up the input if the game window is not focused.
@oak steeple

#

Oh and the code is just action.ReadValue<float>()

oak steeple
#

Thank you! That is so simple, lol.

If I wanted to bind the - and = key to the same input, would that just be a 1D axis then?

austere grotto
#

postiive/negative binding

#

(the = key is really the + key)

oak steeple
# oak steeple Thank you! That is so simple, lol. If I wanted to bind the `-` and `=` key to t...

I suppose that just works.

Follow-up question on that though: If I zoom with the scroll wheel, the zoom moves at a good speed, but when I use the - or = to zoom, it zooms 10x faster. The code is pretty much just this:

 void ZoomCamera(float zoomValue)
    {
        var newOrthographicSize = Mathf.Clamp(mainCamera.orthographicSize + (zoomValue * cameraZoomFactor) , minCameraZoom, maxCameraZoom);
        mainCamera.orthographicSize += cameraZoomFactor * zoomValue;
    }

    // Update is called once per frame
    void Update()
    {
        
        float zoomValue = zoomAction.ReadValue<float>();
        ZoomCamera(zoomValue);
    }

Did I bork something? Or will I just need to discriminate between mouse wheel and - or = inputs and handle them differently?

austere grotto
#

yeah so

#

those are two different styles of input really

#

the key is going to return 1 constantly while it's held doiwn

#

the scrollwheel only gives you value as you're scrolling

#

it might be simpler to just use two separate actions here

#

because the input handling style needs to be totally different due to how those two different controls work

oak steeple
#

Yeah, that makes sense.

#

Tyty, you have been tremendous help!

austere grotto
#

although

#

I think it's possible adding this "Press Only" interaction to the keyboard binding might make it work similarly?

#

Give that a shot

#

nah it doesn't haha

oak steeple
#

yeah, it shouldnt be a big deal, I can just reduce the zoomFactor for those key presses, just always want to make sure I am not straying too far away from good practice

austere grotto
#

hmm this might work tho...

#
    void Update()
    {
        if (Action.action.WasPerformedThisFrame()) {
            Debug.Log(Action.action.ReadValue<float>());
        }
    }```
#

yeah this works

#

it will make it so you have to keep pressing hte - = keys to zoom

#

instead of holding

#

not sure if that's what you want or not

austere grotto
#

so that would necessitate two separate actions I think.

oak steeple
#

yeah, I also need to play with how Orthographic size works with my pixel art (so multiplying by deltaTime might cause issues with the zoom factor), I have heard it can create issues if not scaled correctly shrug I am a noob though

spring herald
austere grotto
#

It won't make the keyboard zoom compensate for varying framerates though

#

Oh but there's a DeltaTime scale processor!

#

That would help

oak steeple
#

Ohhh, that is neat, tyty.

I am very aquainted to handling this all in code, so trying to learn more about this input system

austere grotto
#

yeah I normally handle most of it in code myself and avoid processors

#

but - I guess they can be useful.

onyx sequoia
#

Hello,
I am developing mobile game where I am using new input system, c# jobs and ui toolkit. In my game, I have a button that, when held by the player, spawns specific objects. For that I am using:
RegisterCallback<PointerDownEvent> -> calling function to start spawning objects
RegisterCallback<PointerUpEvent> -> calling function to stop spawning objects

This works on all tested mobile devices except for one that has an Samsung S Pen. When a player with an S Pen holds the button, sometimes the S Pen correctly detects the hold for the entire time, but other times, the PointerUpEvent is called shortly after the touch, even though the S Pen is still touching the screen.

My second issue with the S Pen is that only with it, strange and unpredictable things happen after a random touch—things that don’t make sense and aren’t programmed. Specifically, in my C# job, I have a particle simulation that isn’t affected by input in any way, yet sometimes, after hovering or touching with the S Pen, the particles inexplicably teleport off-screen. When the S Pen is inserted back into its holder, this strange behavior does not occur.

I didn't find any patterns in it, and only this error appeared in the game development console, but I'm not sure if it's related to it:

#0 0xd146/0c7 (libunity.so) Platform Stacktrace:GetStacktrace(int) 0x22
#1 0xd14b6887 (libunity so) Stacktrace::GetStacktrace(int) 0x2
#2 0xdleafa?! (libunity.so) DebugString ToFile(Debug String ToFileData const&) 0x196
#3 0xd0b2a351 (libunity.so) DebugLogHandler Internal Log(LogType, LogOption, core: basic_string<char Core::StringStorageDefault<char> const&, Object) 0x6a
#4 0xd0b2a2c7 (libunity.so) DebuglogHandler_CUSTOM_Internal_Log(LogType, LogOption 
BindingsManagedSpan, void) 0x3a 
#5 0x8405c59a (Unknown) ? OxO

Do you please have any ideas how to fix this issues? Thank you very much! 🙂

austere grotto
onyx sequoia
oblique raven
#

could someone tell me real quick what the action for Look has to be , is it pass through or axis , i tried so much i cant get it wroking

#

Debug.Log(lookAction.ReadValue<Vector2>());

#

this just does not give me any values

#

i remember i had to change something but i cant remember what it was

#

ah never mind it is one of those unity bugs..

#

a new project works as it should be

hidden kindle
#

How do i work with the new input system and mobile gyroscope ?

distant sphinx
#

How would I capture at the very least either a deviceID or an InputUser, just anything that lets me know who pressed a button in UI Toolkit? I'm reading and searching across the docs and all I can see is making it compatible with uGui which requires replacing their event system with the Input System's but I cannot find something about "getting who clicked the thing" or similar

#

Everything from Unity +2022 should be working out of the box according to the docs as well

#

I should note that I'm not using the PlayerInputManager or PlayerInputs

#

The most I've gotten was something like



public class ButtonInputHandler : MonoBehaviour
{
    [SerializeField] private UIDocument uiDocument;
    [SerializeField] private InputActionAsset inputActions;
    private InputAction interactAction;

    void Awake()
    {
        // Find the Interact action in the UI action map... 
        // This... doesn't work in multiplayer because anybody performing the action would be picked up...
        // even more, it doesn't care if you're actually pressing the button or not...
        var uiMap = inputActions.FindActionMap("UI");
        interactAction = uiMap.FindAction("Interact");

        // Get the root visual element and button
        VisualElement root = uiDocument.rootVisualElement;
        Button actionButton = root.Q<Button>("action-button");
        actionButton.clicked += OnButtonClicked;

        interactAction.Enable();
        interactAction.performed += OnInteractPerformed;
    }

    private void OnButtonClicked()
    {
        Debug.Log("Button clicked in UI Toolkit!");
    }

    private void OnInteractPerformed(InputAction.CallbackContext context)
    {
        // Get the device that triggered the action
        InputDevice device = context.control.device;
        int deviceId = device.deviceId;
        Debug.Log($"Interact action performed by device ID: {deviceId}");

        // Get the InputUser associated with the device (if any)
        InputUser? user = InputUser.FindUserPairedToDevice(device);
        if (user.HasValue)
        {
            Debug.Log($"InputUser ID: {user.Value.id}");
        }
        else
        {
            Debug.Log("No InputUser associated with this device.");
        }
    }

}

Which is frankly, insane, and I can't even think how I would communicate the data found in OnInteractPerformed to the button subscribers. It simply just doesn't work.

#

Maybe create a cursor (pool?) which are linked to InputUsers and whenever the button is pressed look at the cursors for who was hovering it? But then the cursors can overlap and nobody knows, that's also an additional whole system to query info for instead of being offered in the button event...

#

Alternatively a "owner player ui" so i already know who's pressing it, but I still have the issue of data not being passed through the event to subscribers and I still don't know who's pressing things so I'd have no way to block other users from pressing the button

distant sphinx
#

I'm been researching a bit more and from my understanding is that I could probably use
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/UISupport.html#multiplayer-uis
And then track every the events generated back to the system that generated them, maybe?
Reading some more and only one EventSystem can exist, in both Unity's and UI Toolkit's, which brings me to MultiplayerEventSystem and its InputSystemUIInputModule, but according to the manual When working with Unity UI (uGUI), or when using UI Toolkit in versions of Unity prior to Unity 2023.2, you must use the UI Input Module component which defines which actions are passed through to your UI, as well as some other UI-related input settings. Brings me to believe that it's entirely optional as I'm in Unity 6 and I'm going in circles

distant sphinx
#

Unless using MultiplayerEventSystem makes InputSystemUIInputModule entirely required, maybe some clarification would be nice...?

alpine dock
#

Was there ever any followup on this?

#

I've got a system with multiple control schemes (RTS, first/third person) and the player is able to activate a "build mode" in either but there are cases where build mode controls need to override different controls in each mode (e.g. the scroll wheel handles zooming in/out in the RTS control scheme, while it handles swapping weapons in the FPS/TPS control scheme) to do the same thing (in build mode it should rotate the object you're building).

Just wondering if this layered action map thing ever got implemented in any capacity before I go and implement my own wrapper, can't find anything relevant in docs.

distant sphinx
#

Considering that the last few replies were about "still dreaming" and some user complaining about having to make their own wrapper... tough chance

#

I think you'll need to write your own wrapper

#

The issue is rather old so I'd go check around first if anybody has made their own implementation

alpine dock
#

eh, it's more trouble integrating someone else's code into my project

#

can you tell I've been a C++ developer for several years

alpine dock
#

okay yeah I didn't realize forums did the infinite scroll thing and not pages now, I guess the idea was to use the timeline thing on the right side lmao

#

I suppose this could be done using bindingMask, but this is ugly as shit lol

distant sphinx
#

This is rebinding the action map itself, I don't think that'd be like, a good idea for gameplay

alpine dock
#

specifically looking at LoadBindingOverridesFromJson

distant sphinx
#

I personally would just have an enum or something with a switch and call Actions.Gameplay.Enable() or Actions.Build.Enable(), and whenever you enable one or the other the other gets .Disable(), if I understand correctly what you want to do...

alpine dock
#

nope

#

build needs to be enabled concurrently with the main control scheme and override its bindings where applicable, while retaining those it doesn't override

distant sphinx
#

Okay so its not a WHOLE map, but rather selective actions

#

Hmm yeah that's complicated

alpine dock
#

It's an action map in the literal sense, but it's not a control scheme in the colloquial sense

#

Action maps do support multiple concurrent action maps (e.g. I have the pause button always enabled lmao)

distant sphinx
#

Yeah that's also what I'm doing (with debug lol)

alpine dock
#

It's just that you can't set input actions to be consumed, so if you press space, it'll be plumbed through to every active action map :')

#

Right now for testing purposes I just have "build mode" jammed into a bool in the main game class 💀

#

but long term I don't wanna have two divergent code paths (one for RTS controls, one for FPS/TPS controls) handling the exact same thing, since that'd just be silly

#

oh well, I'll figure something out, it's not a particularly complicated idea in the first place - just working around the unity API as usual

distant sphinx
#

On top of my head right now I'd look if I could write a helper method that enables the RTS action map and then selectively goes through each action individually of the FPS/TPS action map would be possible, instead of the Action Map itself

#

Extremely hardcoded solution specifically just for this sole gameplay solution

#

But I haven't gone down there yet so I don't even know if you can disable actions individually

#

(I imagine you can)

#

Either that or do bizarre stuff like action processors or modifiers or so

alpine dock
#

Yeah, you can disable them

#

hmm, the annoying thing here is also gonna be dealing with runtime control rebinding (e.g. someone who wants to put rotate on Q/E instead of the mouse wheel)

distant sphinx
#

That's why I think that keeping it to the actions would be the best way instead of doing something like a JsonOverride

alpine dock
#

well, that's the thing, if changing the key eliminates the relevant binding conflict, then you don't want to disable the lower priority binding anymore

#

so if they've rebound rotation they should be able to zoom with the mouse wheel again

#

so i guess it's more that i want input actions to be able to consume key presses lmao

#

I have written fully custom input systems from scratch in the past with full support for this exact kind of thing, but not for Unity, it was in C++ - so I was just intercepting win32 messages and routing them to the input handler

#

I'll have to sit on this and just keep doing the placeholder thing for now I guess, thanks for trying to help though

alpine dock
#

(I'm not familiar enough with the UI toolkit to know anything here, sorry - I'm just writing my own UI through code around the older Unity UI for the sake of mod support)

distant sphinx
#

Literally just made this up right now, don't even know if processors allow you to do something like that but they are events so maybe?

#

This is more like "A reason for why to look into action processors" because I just don't know how they function or how to use them and how far you can get with them, other than the default baby ones like normalize or invert or w/e

distant sphinx
#

So instead of defining UI gameobjects you just load the XML into a single MonoBehaviour and be done with it, it even has CSS so you can just style it with ease

alpine dock
#

and you can modify that file, it'll just get generated over again if you make changes

#

could maybe use a partial class and extension methods though

#

like this shit's all auto generated lmao

alpine dock
#

oh that's why i chose the old UI

#

I wrote my own XML content loader anyway

#

FWIW when I say moddable, I mean I'm developing the game for direct mod support similar to what Rimworld and Kenshi have rather than mods for games like Abiotic Factor of Risk of Rain

distant sphinx
alpine dock
#

oh UI toolkit has worldspace? wacky

distant sphinx
#

...I believe so! I read about it, I think its Unity 6 though?

alpine dock
#

i just so happen to be on 6 lmao

distant sphinx
#

Oh right I guess the ease of "it's just a single component and a single xml" takes away from "GetComponentInChildren" and stuff

alpine dock
#

I'm doing as little work in the editor as possible, FWIW

#

yeah, it's basically condensing the older component hierarchy model into a single element that's more like FXML or WPF

distant sphinx
#

You have to instead use things like search by name

alpine dock
alpine dock
distant sphinx
#

Oh also player models believe it or not

alpine dock
#

I mean that's fairly straightforward I think, a lot of games do XML-based content

#

i.e. you define all your weapons, equipment, etc. through XML

distant sphinx
#

You just have to have a extremely strong serialization and deserialization system

alpine dock
#

eh, C#/.NET has builtins if you can put up with it

#

personally I got sick of the builtin .NET XML stuff

distant sphinx
#

still slightly more complicated than doing something like a ScriptableObject and calling it a day

alpine dock
#

oh for sure

#

some people swear by scriptableobjects but

#

not my thing

#

I used them in past projects for preset stuff like movement controller parameters

#

I just feel like they get a bit more annoying to manage in large quantities :p compared to a text file where I can just ctrl+f something and do mass replaces if I need to

distant sphinx
#

For me it's using DOTS why I want it to be easier to modify, kinda maybe slightly inspired by source's vpks where it's just a filesystem and you can overwrite whatever you want in the game without needing a editor or sdk

alpine dock
#

also we've gotten fairly off topic, whoops

not a huge problem if it's not steamrolling other people asking questions but probably best to move the conversation somewhere idk

distant sphinx
#

I was thinking that as well

onyx sequoia
#

Hello,
it is possible in new input system disable pen input? Thank you! 🙂

austere grotto
onyx sequoia
#

I wrote bug to discussion forum, but noone replyed so far, so my idea was to completely disable pen to not trigger any events...

#

P.S: I am using new input system with ui toolkit, so I am detecting holding button via registercallback pointerupevent and pointerdownevent (I am using this, because on pointerdown event is water opened and on pointerup is closed)

onyx sequoia
opal plaza
#

What is the binding for the left stick press on playstation controller? I cannot seem to find it inside the input system.

grave parrot
#

is there a way to make it so the input system only calls the function once even if the button is held? even when its tapped it gets called more than once.
I tried setting the bool false right after but that's just too quick.
(I have my other scripts reference the input handler script and use the bools to trigger actions like a jump).

austere grotto
#

Your problem presumably is you're reading that bool variable in Update

#

So you're doing it every frame

grave parrot
#

what should i use to read the bool though?

austere grotto
#

I recommend not having it

#

It's an antipattern

grave parrot
#

thank you

next bone
#

In the new input system, how do I make it detect only one press of the arrow keys, while getting their value?

austere grotto
next bone
austere grotto
#

anyway it sounds like you're doing something like checking if it's currently pressed in Update

#

You would need to share your current code - but most likely oyu need to switch from IsPressed() to WasPerformedThisFrame()

#

but I do recommend you simply use the built in navigation rather than reinvent the wheel.

next bone
#

I'd rather code it myself

#
    {
        pauseOpen = pauseOpenAct.WasPressedThisFrame();
        pauseClose = pauseCloseAct.WasPressedThisFrame();
        playerVector = pmAct.ReadValue<Vector2>();
        jumpPressed = jumpAct.WasPressedThisFrame();
        jumpFreed = jumpAct.WasReleasedThisFrame();
        menuVector = mmAct.ReadValue<Vector2>();
        menuChoose = mcAct.WasPressedThisFrame();
    }``` In this input manager
austere grotto
#

terrible pattern

#

don't do this

#

refer to this conversaion I had the other day (and again right above you in this channel)

#

you are making your life much harder with this pattern

next bone
#
    {
        selectButton();
    }

    public void selectButton(){
        numButton=(int)Mathf.Clamp(numButton-inputManager.instance.menuVector.y,0,buttonHolder.transform.childCount-1);
        Debug.Log(numButton);
        for(int x=0; x<buttonHolder.transform.childCount; x++){
            buttonHolder.transform.GetChild(x).GetComponent<Button>().image.color=x==numButton?Color.red:Color.white;
        }
    }```
#

The functions in the menu manager that highlights the buttons

austere grotto
#

so yeah of course it's going to go lightning fast

next bone
#

So when should it be done then

austere grotto
#

Only when you first actuate the stick (or first press the key)

next bone
#

Do I use WasPressedThisFrame()?

austere grotto
#

Again i really recommend just using the built in system

#

If you want this to work with joysticks as well as the keyboard, you're going to have to distill the vector down to a cardinal direction, and then compare the current direction to the previous direction to see if it has changed

#

the built in UI navigation does all this out of the box

next bone
#

How do I use the built in navigation system then?

austere grotto
#

It should pretty much be working out of the box assuming you haven't done anything weird and you're using UGUI

#

you may need to manually select one of the buttons/UI elements in Start or something to kickstart it

#

You may want to double check the highlight colors etc you have set up on your buttons too

next bone
#

@austere grotto Thanks, it works

timid cypress
#

For my "Move" (LeftStick [Gamepad]) Input Actions Binding, I could not find an option to replicate GetAxisRaw, and so the closest I've come is by code ("Round"):

void OnMove(InputValue inputValue) {
    Vector2 inputAxis = inputValue.Get<Vector2>();
    // inputAxis = new Vector2(Mathf.Round(inputAxis.x), Mathf.Round(inputAxis.y));
    Debug.Log(inputAxis);

I've disabled Rounding and using Debug.Log to demonstrate.

Some comments in other channel are:
Chris: inputValue.Get<Vector2>() kinda is the equivalent of GetAxisRaw
rb5300: Maybe this? https://docs.unity3d.com/Packages/com.unity.inputsystem@1.14/manual/Processors.html#axis-deadzone

In my experience, @fierce compass,when I Debug.Log the value of inputValue.Get<Vector2>(), it's showing decimal numbers, not whole numbers.

@small quest , I've checked that doc now, and I've tried 0.5 for min and max, but this doesn't appear to change anything.

Without whole values, I can never get "isMovingLeft" to be true, like it is when I use Round.

#

I've been having a hard time with this. I did however finally get Player Input Manager working to add players manually, so that my 4 children player objects (with Player Input components) are automatically added.

small quest
timid cypress
#

I see the docs for writing my own custom processor. I just wonder, am I really the first person in 5 years to want a GetAxisRaw equivalent.

fierce compass
timid cypress
#

For GetAxisRaw, the value is not smoothed like it is here. "The value will be in the range -1...1 for keyboard and joystick input. Since input is not smoothed, keyboard input will always be either -1, 0 or 1. This is useful if you want to do all smoothing of keyboard input processing yourself."

#

Wait, that quote is emphasizing keyboard input for no smoothing. But, in my experience, I was using a stick on the old input system and getting absolute values of 1, -1, or 0.

#

Creating my own processor, I'm stuck at ```csharp
#if UNITY_EDITOR
[InitializeOnLoad]
#endif

#

oh, I added using UnityEditor above [InitializeOnLoad]

#

yeah, it's working now.

distant sphinx
#

The type or namespace name 'Switch' does not exist in the namespace 'UnityEngine.InputSystem' (are you missing an assembly reference?)
Is Switch only available in Switch builds?

fierce compass
#

i mean, it's an axis

#

it's supposed to be analog

#

the new input system doesn't give smoothing there, it isn't GetAxis
it's just giving actual analog values

it sounds like you were getting bad values from the old input system

timid cypress
#

Strange. I also was experiencing a problem with the old input system where one of my controllers (F310 Logitech Gamepad) GetAxisRaw was always (1, 0). The other controllers (XBOX 360) worked fine (0, 0). This forced me to start using the new input system.

heavy swan
#

I've got an "binding with one modifier" action for alt-Z, but Z-alt is triggering it when I would only expect alt-Z to trigger it. Why is it triggering when the modifier is pressed instead of when the binding is pressed / how to make it work as I want? (This is not about hitting Z by itself like all the topics I found about modifiers)

heavy swan
#
  1. I want to bind a label to two ints: a simple "X/Y" display. But "text" bindingID can only take one property. So. I presume there's no double-binding and I'm gonna have to make struct with the two
austere grotto
heavy swan
#

Yea I'm just sitting in the same channel still

sand shadow
#

Hey i have a silly question - my ui is not working at all with the new input system. Keyboard input works as usual but ui not at all

    public class PlayerInputHandler : MonoBehaviour
    {
        #region Private Fields

        /// <summary>
        /// Instance of the input system actions, which contains all input action maps and actions.
        /// </summary>
        private InputSystem_Actions _inputSystemActions;

        /// <summary>
        /// Tracks whether the input system has been initialized to prevent redundant initialization.
        /// </summary>
        private bool _isInitialized = false;

        #endregion

        #region Public Properties

        public InputSystem_Actions InputSystemActions => _inputSystemActions;

        public Vector3 MousePosition => Mouse.current.position.ReadValue();

        #endregion

        #region Public Methods

        /// <summary>
        /// Initializes the input system actions and enables them.
        /// This method is called via dependency injection to ensure the input system is ready for use.
        /// </summary>
        [Inject]
        public void Initialize()
        {
            // Prevent redundant initialization.
            if (_isInitialized)
            {
                return;
            }

            // Initialize the input system actions if not already initialized.
            _inputSystemActions ??= new InputSystem_Actions();

            // Enable the input system actions to start listening for input.
            _inputSystemActions.Enable();

            // Mark the input system as initialized.
            _isInitialized = true;

            // Log initialization for debugging purposes.
            Debug.Log($"{nameof(PlayerInputHandler)} initialized.");
        }

        #endregion
    }
#

It does not even work in a completly new scene with just a button

#

NEVERMIND! It was the problem that i had the mobile simulator open 😄

meager ginkgo
#

On-screen stick doesn't work.

#

Here's my InputAction control scheme:

#

WASD works here

#

But the on-screen thumbstick doesn't work

#

Keyboard P2 doesn't use the WASD, so this control scheme is definitely active

austere grotto
#

On Screen Stick works in general

vestal crane
#

Made a script to track the current input device, but when using controller, it will randomly throw in keyboard inputs for some reason. I've tried a few different controllers so I know that's not the problem, any ideas?
https://paste.mod.gg/ramzijjwxhrn/0

#

it also seemed to happen differently on switch controller vs xbox

#

on switch, sometimes every part of an input would be read as keyboard, but on xbox it's usually only part of the input

#

only playing on controller

austere grotto
#

that would give more info

vestal crane
#

space is not used in my controls so it must be triggering that on its own

austere grotto
#

xbox?

vestal crane
#

xbox controller

#

looks like the same thing for switch

austere grotto
#

Open the input debugger

#

you must have some rogue device plugged in or something

#

or your cat is on your keyboard

vestal crane
#

it only happens when doing inputs on the controller

#

so I doubt its something else

meager ginkgo
#

The PlayerInputActions asset:

#

Then I generate the C# class from it.

#

Then I have this class that holds the PlayerInput and PlayerInputActions:

#
public class PlayerActionsReporter : MonoBehaviour {
    public PlayerInput PlayerInput;
    public PlayerInputActions PlayerInputActions;

    void Awake() {
        PlayerInputActions = new PlayerInputActions();
        PlayerInput.actions = PlayerInputActions.asset;
        PlayerInput.user.AssociateActionsWithUser(PlayerInputActions);
        PlayerInput.SwitchCurrentControlScheme(PlayerInput.defaultControlScheme Keyboard.current);
    }
}
#

I've done it this way, so I can have multiple control schemes for the same controller and allow multiple players play using the same device or different devices on the same machine.

#

Then I have this class for testing:

#
public class PlayerInputsLogger : MonoBehaviour {
    public PlayerActionsReporter PlayerActionsReporter;
    void Start() {
        PlayerActionsReporter.PlayerInputActions.ActionMap.Movement.performed += _ => Debug.Log($"Movement Performed");
        PlayerActionsReporter.PlayerInputActions.ActionMap.Movement.canceled += _ => Debug.Log($"Movement Cancelled");
    }
}
#

But when I move it in the scene, nothing happens:

austere grotto
#

not sure how it works when you manually assign an actions asset to a PlayerInpuit component but one thing to try is PlayerInputActions.Enable();
I would also try to rule out any control scheme stuff by... eliminating all of your control schemes

meager ginkgo
#

Thank you

#

The way I fixed it yesterday is by enabling it right after creating:

        PlayerInputActions = new();
        PlayerInputActions.Enable();
#

I mean, if it's supposed to be disabled by default, then why does the keyboard work?

austere grotto
#

I don't know

meager ginkgo
#

I think I've read about enabling it in that thread

#

Someone also said that they created their own onscreen stick component

#

In my case I just copied Unity’s component, but removed the parts where it uses the broken buggy Input system.

#

Isn't Unity not open source, what did they mean they copied it?

austere grotto
#

parts of it are open source

#

including the input system

#

most of the packages are open source

meager ginkgo
#

Oh

#

That's very useful to know

meager ginkgo
#

That should be very useful to create my own component, like my own BoxCollider2D but I'd like to work differently to easily mutate hitboxes: instead of only allowing to set location and size, I'd like to also be able to set positions top, bottom, left and right edges of the square.
Because right now I often find myself calculating manually the appropriate location and size, so that my walls end at the correct locations.

#

Like if I want to make another collider at the top to the current one that's also twice as tall as the current one.

#

Now I need to do math to calculate the correct position and size for it and there is no way to set the individual wall positions.

meager ginkgo
#

Now I have another issue with inability to dock the stick to the bottom right corner:

#

It gets bugged and disappears once I press on the stick

#

Then I can't even press on it again after I press it first time.

#

I guess I can still dock it to the center and use a canvas scaler and get pretty much the same effect here.

#

Or I can't. It disappears away from the screen on different aspect ratios.

keen zodiac
#

The key works only the second time you press it. So i have to press it twice to toggle fullscreen. Does anyone know why?

It's the screen toggle that is making it do this but i don't know why. It's not about window focus, because other keys work.

I tried with keys like F11 and M and it's the same result. I tried delaying the fullscreen toggle. No matter what, the game ignores the first time i press the key.

I'm absolutely baffled

    void Update()
    {
        if (fullScreenAction.WasPressedThisFrame())
        {
            Debug.LogError("fs key pressed");

            // It's in fullscreen already, switch to windowed mode
            if (Screen.fullScreenMode == FullScreenMode.ExclusiveFullScreen ||
                Screen.fullScreenMode == FullScreenMode.FullScreenWindow)
            {
                Debug.LogError("to windowed");
                Screen.fullScreenMode = FullScreenMode.Windowed;
            }
            else
            {
                Debug.LogError("to windowed full screen");
                // Switch to windowed fullscreen
                // Screen.fullScreenMode = FullScreenMode.FullScreenWindow;
                Screen.SetResolution(Screen.currentResolution.width, Screen.currentResolution.height, FullScreenMode.FullScreenWindow);
            }
        }
    }
vestal crane
fast compass
#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

[Header("References")]
public Rigidbody rb;
public Transform head;
public Camera camera;

[Header("Configurations")]
public float walkSpeed;
public float runSpeed;

[Header("Runtime")]
Vector3 newVelocity;

void Start() {
    // Nasconde e blocca il cursore
    Cursor.visible = false;
    Cursor.lockState = CursorLockMode.Locked;
}

void Update() {
    // Rotazione orizzontale
    transform.Rotate(Vector3.up * Input.GetAxisRaw("Mouse X") * 2f);

    float speed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
    float inputX = Input.GetAxisRaw("Horizontal");
    float inputZ = Input.GetAxisRaw("Vertical");

    // Ignora piccoli movimenti involontari
    if (Mathf.Abs(inputX) < 0.01f) inputX = 0f;
    if (Mathf.Abs(inputZ) < 0.01f) inputZ = 0f;

    Vector3 inputDirection = new Vector3(inputX, 0, inputZ).normalized;
    Vector3 movement = inputDirection * speed;

    // Mantiene la componente Y attuale
    newVelocity = transform.TransformDirection(movement);
    newVelocity.y = rb.velocity.y;

    rb.velocity = newVelocity;
}

void LateUpdate() {
    // Rotazione verticale (camera)
    Vector3 e = head.eulerAngles;
    e.x -= Input.GetAxisRaw("Mouse Y") * 2f;
    e.x = RestrictAngle(e.x, -85f, 85f);
    head.eulerAngles = e;
}

// Clamp angolo verticale testa
public static float RestrictAngle(float angle, float angleMin, float angleMax) {
    if (angle > 180)
        angle -= 360;
    else if (angle < -180)
        angle += 360;

    if (angle > angleMax)
        angle = angleMax;
    if (angle < angleMin)
        angle = angleMin;

    return angle;
}

}

i have a problem with this code. My player moves by himself when standing still, as if he slides by himself. It also happens sometimes that near the walls he is attracted by them and so if I don't "run" he can't get out of this force, can someone help me?

sonic sageBOT
fierce compass
#

have you tried debugging your values? if you're using a controller you might have to set a dead zone

fast compass
fast compass
#

how can I resolve it?

fierce compass
fast compass
fierce compass
#

don't need to do that, just Debug.Log the values and see if they're what you expect

fast compass
fierce compass
#

a new void... those are methods

#

anyways, no, you would just put those where you want to check the value

fast compass
#

ok

fierce compass
#

logs let you see into the code, you gotta put them where you want to check

fast compass
fierce compass
#

wdym, gravity isn't straight down? your entire world is tilted?

fast compass
#

it is not tilted, if you want I attach some screens and/or videos of what happens

keen zodiac
timid cypress
vague rock
#

Am I just being stupid or what? Why doesn't this do anything?

#

When I add a debug statement it doesn't show when I hit the key I've supposedly bound to "OpenSkillTree"

fierce compass
#

the "Open Input Debugger" on your PlayerInput

#

also make sure it's set to "Send Messages"

vague rock
#

I don't see any of that on the Input Actions window, or in project settings

fierce compass
#

on your PlayerInput

vague rock
#

it's definitely reacting to me pressing K

#

but the scripts aren't

#

And it's set to Send Messages

fierce compass
#

CallbackContext would be used if you set it to "Invoke UnityEvents"

vague rock
#

In that case I wonder if it's this other irritating bug where it's telling me "Value cannot be null" when it's not, because that's on the same script 🙄

fierce compass
#

that wouldve been helpful to know about...

vague rock
#

Nope, it still didn't help. It's whining because the window doesn't exist yet so it thinks the value is null on start up, but even when I turn the menu on by default K isn't closing it

#

and I have K set to close it

fierce compass
#

why not just make a single action for "Toggle Skill Tree" and handle whether to open or close it in code

vague rock
#

I need to disable the character controller and allow the mouse to show up, and I thought using the input system was supposed to easily facilitate that

fierce compass
#

that's pretty unrelated

#

you could do it with the serialized callbacks, but why not just do it all through code in a single method

#
void OnToggleSkillTree() {
  if (skillTreeOpen) {
    // stuff to close skilltree
  } else {
    // stuff to open skilltree
  }
}
#

oh i just noticed opening and closing are on separate action maps, mb

#

i see what you're going for now

#

could you actually show the error then

vague rock
#

here's the layout of the UI_StatTree in UIBuilder, and everything that error is whining about is still there

#

Here's the line it points out in VS

fierce compass
#

okkk so this is kinda outside the scope of the channel, im not familiar with how that UI system works

vague rock
#

I think I'm gonna trash it anyway cause it's not how I want it to look in the long run afterall

#

it's all columns and rows, I want a circle spanning out like PoE (not as big)

fierce compass
#

just a quick reality check; it kinda sounds like you're conflating these systems
how the input system works is detached from how you actually open or close the menu or freeze the PC

vague rock
#

Alright, I might be bashing my head against a brick wall I can just walk around then

#

thanks for your help! 🙂

fierce compass
#

that's not what im saying lol
i just mean; if you have an issue with receiving input, don't expand that issue to other surrounding topics
focus just on the input aspect

or in your case, you seem to have an issue with the UI handling; that's detached from the input system, you would fix that separately

just reduces what you have to think about to solve any given problem

vague rock
#

Yeah that's what I mean, my shitty UI handling is the brick wall but I'm busy playing with the input system thinking it was that

#

and now I can feel my fingernail on the mousepad when I move the mouse so I think it's time for a break

fierce compass
#

rest well and good luck when you come back to it

lime rose
#

Hey, I'm using the following code to detect mouse position

Input.touchCount > 0 ? Input.GetTouch(0).position : Mouse.current.position.ReadValue()

However when I'm on android (with WebGL) and I don't touch the screen, touchCount returns 0 et Mouse.current.position.ReadValue() return Vector2.zero

The documentation state The mouse that was added or updated last or null if there is no mouse connected to the system. however it is never the case for me

How can I detect that my user is on android/webgl and is not touching the screen?

austere grotto
lime rose
#

Uh? Is it?

#

Ah is Input.GetTouch the old input system?

austere grotto
sullen iris
#

Ok I'm really confused about something. I'm getting this error:
InvalidOperationException: Cannot read value of type 'Vector2' from composite 'UnityEngine.InputSystem.Composites.AxisComposite' bound to action 'Player/Move[/Keyboard/leftArrow,/Keyboard/rightArrow,/Keyboard/downArrow,/Keyboard/upArrow,/XInputControllerWindows/dpad/left,/XInputControllerWindows/dpad/right,/XInputControllerWindows/dpad/down,/XInputControllerWindows/dpad/up,/XInputControllerWindows/leftStick,/XInputControllerWindows/leftStick/up,/XInputControllerWindows/leftStick/down,/XInputControllerWindows/leftStick/right,/XInputControllerWindows/leftStick/left,/Keyboard/upArrow,/Keyboard/downArrow,/Keyboard/leftArrow,/Keyboard/rightArrow,/XInputControllerWindows/leftStick/up,/XInputControllerWindows/leftStick/down,/XInputControllerWindows/leftStick/left,/XInputControllerWindows/leftStick/right,/XInputControllerWindows/dpad]' (composite is a 'Int32' with value type 'float')
By the looks of it, this error can be fixed by setting the corresponding action to Action Type "value" and Control Type "Vector2". You then add the bindings as 2D Vector composites. So why, then, could I still be getting the same error?

#

"Controller Movement" is tested with the Xbox control stick and that is the only control scheme of the three that actually works. The other two run an error like the one I posted above

#

The help I've found online always points to the Action Type being the culprit but I'm pretty sure I've already covered all the places that would cause this error.

#

This is the exact line that triggers the error because it can't get a Vector2 out of it.... even though as far as I can tell it really should be able to?

#

The options for my keyboard here just to show they're set to 2D Vector

#

If there's anything else I should post that would add necessary context then pls let me know

sullen iris
#

I tried making a new input system from scratch by adding one from the Player Input component when when I plugged that in... it worked fine. In spite of the fact that I swear the options selected are identical to mine

fierce compass
#

was it perhaps unsaved?

#

that was the first thing i thought of

#

if it was maybe it was just bad caching that mightve been fixed with a restart

sullen iris
#

It was definitely saved

#

Maybe bad caching. Because honestly that did not feel right at all. I'm really convinced I had everything covered that time

lethal tiger
#

Can someone here help me out? I'm new to Unity, and I try to make a script, so my player, rotates in the direction of the mouse cursor, but it doesn't work.

using UnityEngine;

public class PlayerRotationHandler : MonoBehaviour
{
    [SerializeField] float rotatingSpeed = 5f;
    [SerializeField] InputSystem_Actions inputActions;
    private Vector2 rotation;

    private void Awake()
    {
        inputActions = new InputSystem_Actions();
    }
    private void Rotating()
    {
        Vector2 current = inputActions.Player.Look.ReadValue<Vector2>();
        rotation.x += current.x;
        Debug.Log(rotation);
        transform.localRotation = Quaternion.Euler(0, rotation.x, 0);
    }

    private void FixedUpdate()
    {
        Rotating();
    }
}

I am using the input system version 1.14.0. and the Default Action map.
The Debug log gives me a zero vector.

lethal tiger
#

Okay, nevermind, I got it.

torpid silo
#

Any idea why my Mouse Position isn't reporting in the Debug.log? I'm holding right-click when I'm testing like the modifier wants. It's also part of the Keyboard scheme that I created.

It works when my Gamepad thumbstick/scheme is used.

public void OnAim(InputAction.CallbackContext context) { _aimInput = context.ReadValue<Vector2>(); Debug.Log(_aimInput); }

austere grotto
torpid silo
#

For (2), yes. For (1), using the Player Input component.

austere grotto
torpid silo
austere grotto
torpid silo
#

The callback isn't being fired when the mouse input is used, in order words. Not sure why.

#

I have both of them bound to the Keyboard scheme that I made. My keyboard inputs for movement (WASD) work fine as well.

austere grotto
torpid silo
#

Gonna restart the editor, who knows.

austere grotto
#

and not delta

#

on the mouse?

#

delta is much more analagous to a joystick

torpid silo
#

I think so. Trying to do a top-down aim where I rotate the player after right-clicking, similar to an aim. Wanted to see if I could avoid doing a Raycast by just pulling the position and converting it to world space.

austere grotto
#

I wouldn't do those on the same input action - you'd have to put some nasty logic to check if it's the mouse or the joystick and then do your math no?

#

also you would need the mouse position whether you're doing raycast or not

torpid silo
#

I figure it's either (a) doing an if-check on the scheme, or (b) creating two separate functions to handle the different input actions. Which, yea, would probably be cleaner, but still have to code two things either way.

#

Doesn't work even if I switch it to Delta, aaaaah. I'll keep fiddling with it.

#

It's like my mouse is just not being received by the game lol

austere grotto
#

but yeah that kind of thing really screams "control scheme issue" usually

torpid silo
#

Never used it before but I think I'm looking at it right... WASD is showing up on the Events list as I press them but my mouse is not.

#

Not even left, middle or right click. And it looks like inputs that I don't even have bound to an input action are showing up if I press them, but the mouse is not. It's like Unity isn't even capturing the mouse for some reason.

austere grotto
#

try restarting?

torpid silo
#

I restarted the editor a minute ago but that didn't work. I'll restart my PC real quick.

#

Restarting didn't work, so I deleted both of my Control Schemes like you thought - and now it does. No clue why that's the issue when my WASD was assigned to the same scheme and working just fine. Going to try re-creating them and see what happens.

#

Figured it out. My Keyboard scheme had the Keyboard as a Device Type, but not the Mouse. 😔

toxic lintel
#

Is it possible to (with reasonable effort) get this list of bindings in the inspector, or do I need to manually type the paths?

austere grotto
toxic lintel
#

I ended up just automatically filling it, but there are some property drawers in there (sadly marked internal) that might fit the bill.

worldly spoke
#

Hey I'm trying to have split screen multiplayer, how can I differentiate between two controllers which are plugged in at the same time?

austere grotto
#

It also happens to manage splitting the screen if you so wish

worldly spoke
#

Wait really? I made my own system for splitting the screen but I'll check it out.

brave plank
#

Hey all,
I want to add mobile inputs (buttons and joystick) by using new input system.
Is there a way to use On-Screen Control by assigning actions instead of buttons ? For instance, I have jump action, I want to assign that instead of Button South on gamepad.

austere grotto
amber cosmos
#

Hey folks, stumbled upon a weired problem and couldn't find the aswer online. Thought maybe someone here could help me:

I'm using the input system and have an action (Value, Vector2) with several bindings: 2 gamepad axis (Dpad and Left Stick) and 2 composits (WASD and USB Gamepad Buttons 3, 2, Trigger and 4 for a DDR mat).
When accessing the value via ReadValue I only get inputs from the first two. Any ideas what could cause this?

fierce compass
amber cosmos
#

The keyboard Composite is, but as far as I am aware ReadValue ignores the active ControlSheme, no?
In any case the USB Gamepad composite uses the same controlSheme as the working gampad axis.

fierce compass
#

ah i was thinking of the wrong thing

#

have you tried the input debugger

brave plank
austere grotto
#

what's wrong with using OnScreenControls in its intended form?

brave plank
#

Is it not one of the problems which this input system tried to solve ? I wonder why we have key selection for OnScreenControl.

austere grotto
#

then the analogy will make sense

brave plank
amber cosmos
#

found the answer (or at least part of it). Apparently the mat is considered a joystick, despite being recognized as USB gamepad. After enabling the binding for the joystick controlSheme it worked.

austere grotto
heavy swan
austere grotto
heavy swan
#

well, that is wild it's not a built-in feature to handle a very common thing like that

heavy swan
#

I'm finding that if I Disable() an ActionMap in Start(), it is somehow reenabled and triggering callbacks. I've Disabled action maps elsewhere mid-game and it works fine, but I just added a new map (for targeting) that should start disabled until I call Enable(). (Note this isn't for PlayerActions that seems to often have a similar problem) Alternatively I could subscribe/unsubscribed to the .performed of each action instead of enabling/disabling the map, but that's a bit much. Also maybe I could use some insight on how best to handle the context of input, e.g. the difference between mouse selecting a unit vs targeting a unit's action. Currently going with: turning on/off action maps.

#

While I'm here I don't suppose there's a way to debug breakpoint inside ActionMap.Enable so I could tell where it's being re-enabled...

verbal remnant
heavy swan
#

Yea that's some good rubberducking there, I should just try. I forget that package is in my project's library... still, what about core Unity source though

heavy swan
#

Well, Entering Play Mode turns them all back on, somehow after Start(), but also UI Toolkit is turning all the action maps on also, somehow even after the first frame, so I need to start a coroutune to wait 2 frames before turning off the action map.

verbal breach
#

why do i keep getting this error when i recompile or play?

fierce compass
meager ginkgo
#

How to swap sprites on OnScreenButton?

#

Like when it's pressed.

#

I am thinking to write my own OnScreenButton that would report when it's pressed and released and also swap sprites like the normal buttons do.

#

public class BetterOnScreenButton : OnScreenButton {

    [UsedImplicitly]
    public new void OnPointerDown(PointerEventData EventData) {
        base.OnPointerDown(EventData);
        Debug.Log("On-screen button pressed.");
    }

    [UsedImplicitly]
    public new void OnPointerUp(PointerEventData EventData) {
        base.OnPointerUp(EventData);
        Debug.Log("On-screen button released.");
    }
}

But this doesn't work. The button functionality itself works, but it doesn't debug print.

#

Interesting, explicitly defining that my class implements the interfaces: public class BetterOnScreenButton : OnScreenButton, IPointerDownHandler, IPointerUpHandler made it work.

#

I thought the inheritance is supposed to inherit the interfaces that are implemented in the base classes.

#

Ok this did it:

public class BetterOnScreenButton : OnScreenButton, IPointerDownHandler, IPointerUpHandler {
    Image Image;
    Sprite ButtonUp;
    public Sprite ButtonDown;
    public event Action PointerDown;
    public event Action PointerUp;

    public void Start() {
        Image = GetComponent<Image>();
        ButtonUp = Image.sprite;
    }

    [UsedImplicitly]
    public new void OnPointerDown(PointerEventData EventData) {
        base.OnPointerDown(EventData);
        Image.sprite = ButtonDown;
        PointerDown?.Invoke();
    }

    [UsedImplicitly]
    public new void OnPointerUp(PointerEventData EventData) {
        base.OnPointerUp(EventData);
        Image.sprite = ButtonUp;
        PointerUp?.Invoke();
    }
}
verbal remnant
verbal breach
heavy swan
#

Also maybe 1.14 wasn't needed and this InputSystem setting would've done it :

#

I remember seeing this setting and thought it prevented something like a "W" action being triggered when a "Shift-W" action existed. I guess it does that, but also and prevents "W-Shift" from triggering

heavy swan
#

"Enable Input Consumption" yup now I don't get Z-Alt triggering callbacks

surreal coral
#

hi my INputActions are not working

#

I am using the one directly from unity, I generated a C# Class, added another Script but it is not getting any input into the script, when I change bools from action, it works, but pressing the button to activate the action itself is not working

austere grotto
#

did you remember to enable the instance of the generated class?

surreal coral
austere grotto
#

You named your method "Onable"

#

it should be "OnEnable"

#

also I would highly discourage this pattern of using intermediate variables to capture the input

surreal coral
#

how would you do it?

surreal coral
austere grotto
#

basically - remove the middleman

#

or at least, simplify the middleman

#

With these middleman variables you're basically doubling the work and code you have to write for no real benefit

#

There's only one good reason to use a pattern like this and it's if you want to implement networked multiplayer or AI characters using an input packet command pattern.

surreal coral
#

I am planning on adding multiplayer and Ai characters

austere grotto
#

there's a lot more work to be done here then

#

you need to capture all the input and put it in a struct

#

that struct would need to be network serializable

#

then you would pass that struct around into your various character behaviour scripts to actualyl control the thing.
The Ai would generate these structs as if it were using its own input devices
And the input struct would be sent to the server in an RPC and then the server would control the character using them

#

If you are trying to make a networked online game and you haven't started the networking stuff yet, you should start it, yesterday

#

Networking is best introduced at the very beginning of the project.

surreal coral
#

ohh thats a good advice, im trying to add input system to a package I already have, but maybe I should start focussing on adding Networking forst

austere grotto
#

yeah this whole thing is going to depend heavily on which network framework you use too

surreal coral
#

I still dont know wich Im using, I have always had trouble with Unity netcode, but I havent tryed any other

heavy swan
#

Okay, Continuing from my problems which I thought were solved with "Enable Input Consumption"

#

Now my WASD camera panning input is not triggering at all, and if I turn off that option, it works

#

No other action uses any of WASD, so there should not be any "consumption" problems preventing that Pan from working

narrow talon
#

Hi guys

#

I have a problem with the camera

heavy swan
#

I'm perplexed but going to have to turn the setting off, then manually set the Modifiers order on my alt-z action, individually .

flint snow
#

Hello there
does anyone know a way to read sixaxis data from a DualSense controller on PC?

surreal coral
#

I have a big question, Im changing camera rotation speed, but it seems that the speed its different from a gamepad or controller to delta or mouse, how can I have them be teh same? or should i mae different sensitivities for controller and mouse?

austere grotto
surreal coral
#

but, should i have different values for a mouse sentivity and controller sentitivity

#

I have an Upd&Down and Left&Right Speed

#

wich seems nice when I use controller, but when using mouse, it is too fast

austere grotto
#

yes

surreal coral
#

I have the same Look input action, should I make one for mouse and another one for controller?

austere grotto
#

you should have a separate mouse sentivity

surreal coral
#

okay okay

scenic quiver
#

why use Unity New Input system instead of just Input.GetKeyDown(KeyCode.SPACE) and other stuff?

austere grotto
#

If you don't need any of that, and you just want a very simple programming interface, it's fine to stick with the old one.

scenic quiver
#

ohh ok ok very cool (nah ima learn it, I just always skipped it in tutorials cause i taught no one used it)

#

thanks for the info 🫡

austere grotto
#

Most people are using it other than people who are just getting started with unity.

#

Also afaik it's the default in new projects.

scenic quiver
#

yea lol

austere grotto
#

It definitely has more of a learning curve though

scenic quiver
#

alr thanks 👍

frank bison
#

Hey y'all - I'm making a simple 2D top-down game where the user primarily operates via click and drag. Think of it like a slingshot, clicking, and setting a direction and a velocity, and releasing.

I'm trying to find the best way to do this using the new input system. I understand I could get away with static references to Touches or Input, but I'd rather learn the right way even if it means a bit slower going.

There are two approaches I can see working, and I don't know if one is obviously better than the other.

  • Have each component instantiate a new instance of the generated input system code on Awake. For instance, I can have a SlingshotController with code like private void Awake() { var input = new InputSystem(); input.GamePlay.Click.start += BeginSlingshot; input.GamePlay.Click.Canceled += EndSlingshot; };
  • I can create some sort of generic set of interfaces like IClickable, and then do object collision detection on the point that was clicked. This eliminates the boilerplate of injecting the actions system by itself and registering the event handles, but feels like I might be over-architecting it?
#

I'm also seeing solutions like using the PlayerInput component, and I don't understand yet what IClickHandler and how those events fit into the broader pattern yet.

austere grotto
#

As for clicking and dragging and stuff though, there's a good argument to be made to use the UI event system for it - since it will automatically give you UI-blocking behavior out of the box, and you can use stuff like IDragHandler, IPointerDownHandler, IPointerUpHandler, IBeginDrag, etc out of the box

frank bison
#

These interfaces you mention I see referenced commonly as it relates to UI elements, but I'm also primarily interested (for now) in the gameplay loop and its input handling

austere grotto
#

and when you do so, it interacts perfectly as you expect with UI (i.e. you cannot click through UI)

austere grotto
frank bison
#

Got it. I'll try investigating more down this path. I do generally like the idea of attaching controls via interface implementations and things "just work"

alpine thorn
#

im working on isometric movement game, i setup an playermovement script using the default InputSystem_Actions but upon starting up the game the capsule doesnt move, i have no idea what to do now

#

pls someone respond 😭

austere grotto
#

E.g. inputActions.Enable()

alpine thorn
austere grotto
alpine thorn
alpine thorn
#

looks like there's a problem here

fierce compass
#

!code

sonic sageBOT
fierce compass
#

which one is line 34?

#

maybe share the entire script in one of the websites listed there

alpine thorn
fierce compass
#

is inputActions assigned?

alpine thorn
#

pretty sure they r , i assigned them to unity default input system actions

austere grotto
#

The inputActions variable itself

#

It's a code question

alpine thorn
#

yes it is

austere grotto
#

Have you recently saved the code for that script?

#

Maybe you have unsaved changes

alpine thorn
#

yeah i did

#

i saved them

austere grotto
#

Because from what I see rb is not assigned

alpine thorn
austere grotto
#

That all seems right to me.. are you sure you don't have any extra copies of the script in the scene or something like that?

alpine thorn
#

pretty sure i dont

#

or the input action c# file couldve been generated wrongly considering i also put the script in the scripts folder

#

just regenrated it and it still doesnt work :((

alpine thorn
#

when i was moving in game and went back to scene the capsule moves and the camera locks to it

#

but in game nothing is happening its like a frozen window

#

turns out it was nvr a movement issue

#

it was a caemra issue

atomic galleon
#

hi there
i tried to edit bindings of default UI action map, i wanted to add gamepad right stick to ScrollWheel action and remove it from Navigate action but for some reason when i do so Unity ignores changes so right stick keeps working as navigation and doesn't scroll, i also added LT and RT but it ignores it
i tried to restart Unity, reimport InputSystem asset and script but it didn't help

#

is this a problem with InputSystem or UI scripts?

verbal remnant
verbal remnant
# atomic galleon yes

is it referencing an input action asset in the /Assets folder, i.e. outside the Packages folder?

fair wigeon
#

i'm trying to figure out input prompts,
for them i'm using the GetBindingDisplayString() method (with default args) on the InputAction i need, which instead of returning the input for the current control scheme, however it instead returns both of them ("Q | Y" (button north on gamepad)), and i can't seem to find a way to get it to return the current control scheme
i'm wondering, is there a simple way to make it use the current control scheme or do i have to somehow do it manually?

atomic galleon
#

.inputactions

atomic galleon
#

i just checked does this file even changes when i edit it in Unity and yes, i found all bindings i added and made sure there's no right stick in Navigate and it is in ScrollWheel action, so i can say this is not InputSystem's fault

atomic galleon
#

but there's another problem, each time i push the stick ot scrolls only once instead of scrolling continuously

#

how can i make it scroll continuously, like make it think that i push and release the stick very fast

proper musk
#

Hi. I'm using Player Input to handle Xbox Controller Input. I'm having an issue where my code isn't being run if the Controller is connected after the scene is loaded. Is there a specific way I should handle this?

peak coral
#

hi i am using playerinput in my fps game but i cant move the camera and also cant fire how do i fix it?

austere grotto
#

Show your code, screenshots of your input action configurations, inspectors, etc

peak coral
#

can you dm me i can show you anything you need on a call?

austere grotto
#

No.

#

Make a thread and share screenshots and code

peak coral
#

can you dm me i can show you anything

plucky rain
latent juniper
#

so question.... what exactly is the Joystick input for vs Gamepad? do games really use this?

#

I am asking because I believe this is responsible for it moving in the top left direction for a character controller, cause it thinks it is moving but it really isn't

because I am noticing that when I remove the "Joystick" then it stops moving top left direction

#

and im not sure how AndroidJoyStick got in there, but GMMK 3 HE is my keyboard (which I also don't know how it got there)

fierce compass
latent juniper
#

I mean I guess I can just remove the Joystick controller type entirely and use KBM and Gamepad only and that fixes the issue of my character drifting.. but I'd rather also learn why

fierce compass
latent juniper
#

*also not sure how AndroidJoystick is there either... but 🤷‍♂️ * (since the other Joystick binds says there is nothing binded for that specific map or whatever)

fierce compass
#

it isn't specific to your project or your setup

#

that's just what "Stick [Joystick]" is defined as apparently

fierce compass
#

ah wait im mistaken somewhat; it's kinda the other way around in the case of the specific devices
your keyboard tells your os what it's able to do and unity picks up on that

#

From the input system perspective, everything that is not a Gamepad and that has at least one stick and one trigger control is considered a candidate for being a joystick.

plucky rain
#

Hello, anyone else had issues when using

ruby needle
austere grotto
#

managing a single instance of the PlayerInpuitActions object is good

#

but you shouldn't have this particular script do anything more than just manage and share that instance

ruby needle
#

thank you, let me see how I can make it better

ruby needle
austere grotto
#

let each individual script set up event subscriptions or just poll things in Update

#

basically let each script individually do whatever is best for that script

#

without an unecessary middleman which just adds busywork

ruby needle
#

Alright thank you so much, got it now

paper owl
#

3d model done

ruby needle
austere grotto
pallid iris
#

hey can anyone help to make the player movement (first person) for android ?
(I think this is the correct channel to ask. Tell if i am wrong)
Thank you

fierce compass
#

have you tried googling for tutorials?

meager ginkgo
#

Working on the any key to skip scenes.

#

Wrote this for keyboard and gamepads:

#
    public bool IsAnyButtonPressed() {
        foreach(InputDevice Device in InputSystem.devices) {
            foreach(InputControl Control in Device.allControls) {
                if(Control is ButtonControl { wasPressedThisFrame: true } ButtonControl) {
                    return true;
                }
            }
        }

        return false;
    }
#

How do I detect if the screen was touched?

#

So that it also works on devices with touch screens

austere grotto
#

Tldr; you can make a regular input action and bind it to all button controls with wildcards

severe garden
#

hello I just switched to the new input system due to inconsistencies with the old system with controller binds
i still want to have a keyboard working, but it doesn't appear as an option

i don't have "keyboard" as a binding i can use.
it does appear in the input debugger though and I can select it when creating a new control scheme

im on macos and i have tried using version 2022.3.8f and 2022.3.62f

fierce compass
severe garden
#

i can't listen to keyboard presses and typing keyboard or space doesn't work unfortunately no

fierce compass
#

what about restarting the editor?

severe garden
#

have tried already multiple times. i also upgraded the unity version to the newest

#

i can try again

fierce compass
#

what about input system version?

severe garden
#

im on 1.14.0

#

should i try downgrading?

fierce compass
#

i got nothing

severe garden
#

alright, thanks though

#

okay, after deleting the library, downgrading again using version control and deleting the input action and creating a new one it works somehow

toxic lintel
#

Having some issues with Proton on Steam Deck. A user is reporting that an action I mapped to "button south", is mapped to the B key, which should be east.

No idea if other keys are off too, but I've mapped everything to be generic and tested on an Xbox pad.

toxic lintel
#

I asked AI and it blamed Nintendo 🙂

austere grotto
toxic lintel
#

Unity 6.0, no idea what version of the input system.

austere grotto
#

Check

#

in the package manager

#

also UInity 6.0 is not very specific

toxic lintel
#

I'll check when I get home

austere grotto
#

show the full version

#

Ah, I assumed you were at your computer and ready to debug the issue.

#

I remember there being some bugs with this kind of thing in the past, if you're on an old version of the input system it's possible you're on a version where it hasn't been fixed yet and you might be able to fix it by upgrading.

toxic lintel
#

I hope it's that. Though I generally update packages when I update the engine and I'm on a fairly recent version.

toxic lintel
granite apex
#

Does anyone know what to do if UnityEngineInternal.Input.NativeInputSystem:NotifyBeforeUpdate returns value in addition to the Update from actionTriggered callback? Is this a normal behaviour?

random geode
#

Anybody know a quick and dirty way to get ALL input from a PlayerInput, not just mapped ones? For context as to what I'm trying to do, I have a multiplayer game and I'm trying to show all of a player's inputs on-screen, mapping to every button (especially on Keyboard) would be a pain in the butt.

austere grotto
random geode
#

Sent a lil donation your way

austere grotto
#

Thank you!

toxic lintel
turbid warren
#

in android emulator, when i click on screen without releasing, i get both OnPointerDown and OnPointerUp events triggering . has this happened to you guys before? And the OnPointerDown triggers 2x too..

using UnityEngine;
using UnityEngine.EventSystems;

public class Card : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler, IBeginDragHandler, IDragHandler, IEndDragHandler, IArcLayoutable
drowsy knoll
#

switching display modes seems to cause a missing reference exception in this input system script? There's some code on substack that replaces it and makes it work but it seems like changing it isn't a good idea. Any suggestions?

#

its in InputSystemUIInputModule at line 476

austere grotto
#

But I'm going to mention that you are using the ? operator here with Unity objects which is a big nono

#

And often leads to precisely this kind of issue

drowsy knoll
#

should i just go ahead and change it? the editor gives me a warning and it doesnt seem too future proof

austere grotto
#

You should not use ? with Unity objects.

#

If you are doing that anywhere, you should change it

drowsy knoll
#

this aint my code bro its source code

austere grotto
#

Wdym by "source code"

drowsy knoll
#

its in the code for the event syustem

austere grotto
#

Ah

drowsy knoll
#

when i click the error it takes me here

austere grotto
#

Which line exactly has the error?

drowsy knoll
austere grotto
#

That's very unfortunate and seems like a bug in the input system

drowsy knoll
#

yeah

austere grotto
#

Are you on the latest version?

drowsy knoll
#

im a little behind 6000.022f1

#

but this is in the "2021 or newer" region so it looks ancient

austere grotto
#

More specifically I mean the input system version

drowsy knoll
#

let me check

#

i was 1 version behind ill test it again

#

oh man that fixed it

#

ty

tropic minnow
#

for some reason my player1 input action maps are controlling both player1 AND player2? player2 works fine though?

#
public void OnMove(InputValue value)
{
    // Read input from the new Input System
    movementInput = value.Get<float>();
}```
#

btw a debug log Debug.Log("moved " + this); in onmove shows it's moving them both when onmove is called from player1

austere grotto
brazen pewter
#

how do i make it so holding up diagonal on my gamepad doesnt slow my player down? up really shouldnt do anything at all, just left and right for movement and holding down for crouching

austere grotto
#

It should be set as:
Action Type: Value
Control Type: Axis

#

but the reason "up diagonal" on your gamepad is slowing you down is simply because, for example "diagonal up/right" is just less "right" then simply holding all the way to the right.

#

As you can imagine, the point in red has a larger X value than the point in blue.

brazen pewter
#

i see, what do i need to change so that it's either 1 or 0 then?

fierce compass
#

"normalize" the value you get by taking its Math.Sign

austere grotto
fierce compass
#

if you use Math you don't need to check for 0 since Math.Sign handles 0 correctly

austere grotto
#

or if you're using SendMessages:

void OnMove(InputValue iVal) {
  float axisValue = iVal.ReadValue<float>();
  if (axisValue != 0) axisValue = Mathf.Sign(axisValue);
}```
fierce compass
#

why doesn't Mathf.Sign handle 0 anyways

austere grotto
#

who knows

austere grotto
fierce compass
#

sgn is supposed to
a ton of Mathf methods delegate to Math anyways, and the ones that don't but have equivalents have the same behaviour
this is just... a weird outlier, i guess

brazen pewter
#

working now, thank you all for the explanation and help!

#

hmm one more issue, my jump (action type Button), is pretty inconsistent with the gamepad. sometimes the character jumps and other times not. no issues when using keyboard controls. in my HandleInput function (called in update), the debug is firing every time that jump is pressed but the character doesnt always actually jump. any ideas why its behaving like this?

inputJump = playerInput.actions["Jump"].WasPressedThisFrame();
if (inputJump)
{
    Debug.Log("Jump pressed");
}
austere grotto
#

Also where and how does the inputJump variable get used?

#

If inputJump gets used in FixedUpdate, that's your issue. You can fix it by changing to this:

if (playerInput.actions["Jump"].WasPressedThisFrame()) {
  inputJump = true;
}```
#

or:
inputJump |= playerInput.actions["Jump"].WasPressedThisFrame();

brazen pewter
#

HandleInput is in update, HandleMovement is in fixed update. the block of code i showed is in update

austere grotto
#

the issue is that Update runs much more frequently than FixedUpdate

#

so you might get the true one frame, then it becomes false the next frame, then FixedUpdate runs, never having seen the one true frame

brazen pewter
#

hmm, why dont i see the inconsistency with keyboard controls and only gamepad though?

austere grotto
#

probably just by chance

#

idk tbh, you should definitely see it with both

#

but try my fix, see if it helps

#

oh also

#

you will need to do inputJump = false; in FixedUpdate after the jump code.

#

otherwise it will get stuck to true forever 😛

#

think of it as "consuming" the intent of the player to jump.

brazen pewter
#

yeah this seems much better now, thank you again

fierce compass
#

(my mind still considers 30fps normal)

livid glade
#

Can someone explain to me how I use this component with "Invoke C Sharp Events" selected?

austere grotto
#

Basically - I don't think it's what you want.

#

These 4 events will be triggered

livid glade
#

ah ok.

#

Why would you think I don't want it?

austere grotto
#

because I've never seen anyone use onActionTriggered

livid glade
#

well I'd like to use c# events instead of unity events, but I want to support local co-op without any extra work on my end.

austere grotto
livid glade
#
        private void OnEnable()
        {
            var playerInput = GetComponent<PlayerInput>();
            var actionMap = playerInput.actions.FindActionMap(_settings.inputActionMapName);
            var action = actionMap.FindAction(_settings.movementActionName);
            action.performed += PlayerInputOnonActionTriggered;
        }
austere grotto
#

for example:

PlayerInput playerInput;

void Awake() {
  playerInput = GetComponent<PlayerInput>();
  InputActionAsset asset = playerInput.actions;
  InputAction moveAction = asset["Player/Move"];
  moveAction.performed += MoveHandler;
}

void Movehandler(InputAction.CallbackContext ctx) {
  // handle input here
}```
#

for example

#

yeah

#

I just want to point out that you can do this no matter what setting you have for the behaviour field on the PlayerInput component

#

"Invoke C Sharp Events" just enables onActionTriggered

#

you're basically bypassing the PlayerInput component like this. There's still a benefit because you get the PlayerInputManager device handling stuff out of it

livid glade
#

ah okay. Will this work with multiple instances of PlayerInput for local co op?

austere grotto
#

yep

livid glade
#

ah

#

yea that's the main benifit I want. I feel that the PlayerInput component is almost useless lol

austere grotto
#

agreed

charred swallow
#

the tutorial I'm following's input system thing has an action folder in action properties but in my version it's not there
do I need to worry about this and what should I do instead?
I want to add movement

austere grotto
charred swallow
#

on the right but nvm I found another way

austere grotto
#

In your screenshot on the left you have a Binding selected

#

not an action, @charred swallow

charred swallow
#

oh yeah right

#

thanks

misty swan
#

Is it recommended to always have active input handling set to both? It seems like every "new input system" tutorial i find doesn't work unless I set the active input handling to both in project settings -> player

fierce compass
austere grotto
fierce compass
#

if you have to set it to both then sounds like you're also using the old input system though

misty swan
#

I was doing a CodeMonkey tutorial that was 3 years old so maybe that was the problem but my ball wouldn't jump until I set it to both. Maybe the tutorial is too old maybe:
https://www.youtube.com/watch?v=Yjee_e4fICc

✅ Get the FULL course here at 80% OFF!! 🌍 https://unitycodemonkey.com/courseultimateoverview.php
👍 Learn how to make BETTER games FASTER by using all the Unity Tools and Features at your disposal!
👇
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish....

▶ Play video
fierce compass
#

did you have errors? what did you have it set to before?

misty swan
#

There weren't any errors in the console and it was only set to the new system before. I then changed it to use both without making any other changes and it started working. This was my code and the sphere gameobject had the needed components like rigidbody and player input assigned. The properies for playerinput was also assigned to how it was in the video. Code:

using UnityEngine.InputSystem;


public class TestingInputSystem : MonoBehaviour
{
  private Rigidbody sphereRigidbody;

  private void Awake()
  {
    sphereRigidbody = GetComponent<Rigidbody>();
  }
  public void Jump(InputAction.CallbackContext context)
  {
    Debug.Log("Jump" + context.phase);
    sphereRigidbody.AddForce(Vector3.up * 5f, ForceMode.Impulse);
  }
}```
fierce compass
#

!code

sonic sageBOT
fierce compass
#

ok, what if you set it back to "new" only now?

misty swan
#

Just changed it and waiting for project to load back up. Picture of my components:

#

I should have expanded the events section

#

oh, it worked on the new input system...is that normal to have to switch the active input whenever you make changes to the input system?

#

Also I think the jump only works if I select my sphere before entering play mode

misty swan
#

Thank you for all the help! I'll take another crack at it tomorrow morning. Honestly I should probably look into some unity C# videos before using C# to program these input actions. I feel like every time I see private or public void awake, start, update, OnDestroy I get super tripped up so maybe I'm skipping a step here

fierce compass
#

could skip parts you already know but at least go through it to make sure you aren't missing anything

misty swan
#

Will check it out! There is that junior pathway I see in there I haven't completed yet so that might be a good thing to tackle this week before moving on to input actions

echo cosmos
#

Epic movment scripts uning input system

strong trellis
#

How would I go about having it where it just checks if the player pressed anything?

#

I was trying to make a QTE system, so I have a scriptable object holding the QTE options with their images and whatever the player is supposed to press, and I want to check if the player presses anything. And whatever they press, I save it as a string, and check it against the string in the scriptable object. If it matches, they go to the next, and if its not, they fail.

#

perhaps this is it?

tight merlin
#

Im studying how to be more modular when coding. Is it a good practice to make ScriptableObjects that only has an InputActionReference for Inputs?

so if my player has a LEFT and RIGHT movement I make 2 public variables of that ScriptableObject for left and right and then drag N drop specific keys in. Is this a good/clean way of doing it?

austere grotto
tight merlin
#

thanks for the input tho you have a good point it would be bad design to do it for every Input without reason

austere grotto
tight merlin
merry parrot
#

hey, after upgrading to Unity 6, the scrolling logic is completley messed up. Mac OS scrolling is ridiculously fast, and other platforms are also way faster than they were before.
Was there any change to the values being reported by pointers?

toxic lintel
merry parrot
#

wait, is it this?

leaden belfry
#

i tried everything but i am not able to get the default jump input action button in the cancelled phase

  • i tried setting it press and released interaction type
  • i tried the hold type

but what it does is it directly goes into waiting phase

leaden belfry
# fierce compass also how are you receiving the input?

I am new to unity so i might be doing it wrong i tried reading the new input system docs and this is where i end up

using UnityEngine;
using UnityEngine.InputSystem;

public class Jump : MonoBehaviour
{
    [Header("Ground Sensor Property")]
    public Transform sensorPosition;
    public Vector2 sensorSize;
    public GameObject sensorPrefab;
    public LayerMask GroundLayer;


    [Header("Jump Properties")]
    public GameObject mainObject;
    public float jumpForce = 10f;
    private Rigidbody2D body;
    private InputAction jumpAction;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        body = mainObject.GetComponent<Rigidbody2D>();
        jumpAction = InputSystem.actions.FindAction("Jump");
    }

    // Update is called once per frame
    void Update()
    {
        PlayerJump();
        Debug.Log(jumpAction.phase); 
    }
    public void PlayerJump() { 
        if(jumpAction.phase == InputActionPhase.Performed)
        {
         body.linearVelocityY = jumpForce;   
        }
        if(jumpAction.phase == InputActionPhase.Canceled)
        {
         body.linearVelocityY = body.linearVelocityY*0.5f;   
        }

    }

    public bool isOnFloor()
    {
        if (Physics2D.OverlapBox(sensorPosition.position, sensorSize, 0f, GroundLayer))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.white;
        Gizmos.DrawWireCube(sensorPosition.position, sensorSize);
    }
}```
fierce compass
#

don't you have to Enable the action with that setup?

leaden belfry
#

were the falling is cancelled mid air and enables the variable jump height

leaden belfry
#
 if(jumpAction.WasReleasedThisFrame())
 {
  body.linearVelocityY = body.linearVelocityY*0.5f;   
 }```
#

this fixed my problem

hybrid bluff
#

does the input system work with ninteno switch pro controllers? in the input debugger i get all my inputs but in play mode it just doesnt read the inputs? i saw forum and redddit posts about this but didnt find anyy solution
this is the code i have in Update() to read joyystick inputs:

        throttleInput = controls.Gameplay.Throttle.ReadValue<Vector2>().y;
        steerInput = controls.Gameplay.Steering.ReadValue<Vector2>().x;
#

inputsystem setup

#

ive tried with steam open and closed, still not getting inputs in playmode either way
ive also tried both wired and wireless

hybrid bluff
#

sure, one sec

#
public class Car : MonoBehaviour
{
    PlayerControls controls;
    [Header("Inputs")]
    public float steerInput;
    public float throttleInput;

    void Awake()
    {
        controls = new PlayerControls();
        // controls.Gameplay.Throttle.performed += ctx => throttleInput = ctx.ReadValue<Vector2>().y;
        // controls.Gameplay.Steering.performed += ctx => steerInput = ctx.ReadValue<Vector2>().x;
    }

    void Update()
    {
        // old input system
        // steerInput = Input.GetAxis("Horizontal");
        // throttleInput = Input.GetAxis("Vertical");

        throttleInput = controls.Gameplay.Throttle.ReadValue<Vector2>().y;
        steerInput = controls.Gameplay.Steering.ReadValue<Vector2>().x;
        // Debug.Log(controls.Gameplay.Throttle.ReadValue<Vector2>());

    }
}
#

omitted the steering and phhysics code, ive already confirmed thhat works fine with keyboard inputs.
but i can add that too if you want

#

i have inspector to show the inputs, which showed correctly for myy old input system with keyboard inputs. but now they dont change at all during playmode usingh my controller

hybrid bluff
mystic hearth
#

Yo anyone there??

#

I'm looking for a simple way to create local multiplayer with multiple player prefabs

#

Ping me if u can help

minor pebble
#

after testing a lot of solutions (like using screen size) i still cannot find a correct way to scale touch delta so the movement speed is the same on all devices

austere grotto
fierce compass
mystic hearth
#

aaaaaaaaaaa

#

welll

#

no...

hybrid bluff
#

all working now

misty swan
#

Hey All, I've trying to make a new action map from scratch to learn it all better but am having issues with my mouse movement. I'm trying to set up my Look-Around Action so the player can use there mouse to look around. Right now, when I enter play mode, the camera just spins really fast and moves when I don't move my mouse. Is this how the Action should be set up for mouse?

#

If this looks right I could share what my code looks like

austere grotto
cold lark
#

In order to get input from an ESP32 joystick to Unity, is it XInputController system?

silk ferry
#

How can I clear any pending Input events?

After respawn, my player is reading the last input for movement and resumes that movement once alive again. I've programmatically reset all animations and velocity on death, so the only explanation is a pending input in the input system queue.

misty swan
#

For the most part, do y'all generaly use Invoke Unity Events when setting up controls for your games?

austere grotto
#

I use different things depending on the game.
For the most part I try to avoid PlayerInput except when making a local multiplayer game though.

fierce compass
sonic sageBOT
misty swan
#

Also does anyone know of a good resource that covers 3d movement with the new input system. I've scoured the unity 6 documentation and random videos on youtube but not finding a simple way to just implement jump and wasd. Maybe there is a script out there that I can reference?

uncut yacht
#

You can simply use this in code, no setup of input system needed...

using UnityEngine.InputSystem;
Keyboard keyboard = Keyboard.current;
if (keyboard!=null) {
 if (keyboard.wKey.isPressed) walk forward;
}```
#

There is also Mouse.current, and Gamepad.current.

misty swan
austere grotto
#

That's the only time I use it

uncut yacht
#

Well I read simple move with wasd.

misty swan
#

Sorry misread, do you do the new input system with pass through for actions on local multiplayer?

uncut yacht
#

New inputsystem. No action setup.

#

Simple.

austere grotto
#

I rarely use pass through actions, but there are cases for it

#

Honestly the answer to these questions is all "sometimes, if the circumstances call for it"

#

You need to ask yourself what your goals here are. Are you making a polished game you wish to release and maintain? Is it a hackathon or throwaway project?

#

There are many tutorials out there for various types of game movement using input system

misty swan
# uncut yacht New inputsystem. No action setup.

Maybe I'm making it more complicated than it needs to. I generated a default action map and made a DiscordTest script with the code you provided. I also added the player input component to the player and made the behavior invoke unity events. Should I put your code in a fixedupdate?

fierce compass
#

they can't exist directly in a class

uncut yacht
#

It is for Update like all input.

fierce compass
#

eh, some input can be done outside of that