For those who have the problem of the first start touch always return zero, the workaround is to delay the execution of StartTouchPrimary function in inputManager by 50ms for example private async void StartTouchPrimary(InputAction.CallbackContext ctx) { await Task.Delay(50); OnStartTouch?.Invoke(Utils.ScreenToWorld ...etc } (you can use coroutines or any other way for same thing) (you can do that just for the first time)
Very strange, seems to work, not sure why, would also appreciate an explanation if anyone has one. Btw works with a delay of Task.Delay(1), just to reduce the delay further :)
As usual, incredibly straight-forward and high quality tutorial! I'll definitely be talking about this next devlog, thank you so much for making these :)
Awesome tutorial, thank you. I like how you include most of the code made in other tutorials, so it is possible to understand everything by watching just one video.
If you are watching this, you can also check the Example files from the Package Manager. Input System have changes (1.5.1). There you can find a different way to do this. Support touch, mouse, and pen, at the same time.
I will never be able to reach this person's level. I really wish I would one day have her alertness and professionalism in coding so I can at least keep up with this video with 1x speed
If somebody is struggling with a bug that the very first start position is on the left bottom corner, I have found I guess the easiest solution. In the Input Action window, you need to create one additional action for example 'PrimaryStartPosition' with a binding Touchscreen>Primary Position>Start Position. This one works correctly even with the very first touch. It is a start position of touch, so in code in the InputManager you have to change a function StartTouchPrimary. Basically, you just need to swap playerControls.Touch.PrimaryStartPosition.ReadValue() with playerControls.Touch.PrimaryStartPosition.ReadValue(). Hope it will be helpful for somebody 😅
I was using this tutorial to help me out with my final project, struggled for hours trying to figure out why my touches were stuck in the center of the screen and my debug lines were tiny... your canvas distance needs to be the same as your near clip plane. my group members moved it and I didn't know lol
It works, but when you reload the scene before you end the swipe it makes a NullReferenceException. It still works, nothing breaks, and i think the game doesn`t crash.
Also, anyone know why on the first swipe, the startPosition is always the bottom left position of the canvas? Seems to be the case for @samyam as well here 14:30 on the first line drawn, you can see it starts from the bottom left, even though thats not where she clicks. Any ideas why?
At 14:25, it almost looks like you illustrate your point using a different script (different InputManager) than the one you had been referencing/writing throughout the tutorial beforehand. This admittedly makes it pretty hard to follow, any advice if we're hitting errors here? (For me, no Debug.Drawlines are showing up in my editor when I play.)
So it's been about 10 months since you asked this question. I hope you found an answer by now, but for those who may be facing a similar issue: The issue may well be related to the camera frustum. In the scene view click on your camera. You should see a pyramid shaped outline with the point near your camera. That's the frustum. The ScreenToWorld() method in samyams's video causes the lines and trail to be rendered at the very tip of the frustum nearest the camera. You may have to zoom in on that small portion of the screen to see the lines and trail. There are a few ways to change the behavior. You can move the near clipping plane away from the camera using the camera's inspector. Note that nothing closer to the camera than the near clip plane will be rendered. You can also change ScreenToWorld() to draw the lines at any arbitrary z-depth deeper than the near clipping plane. Note that if you do you may find the trails appear to go through or behind objects in your scene. I did both in my test scene, I had to add a small amount (0.1) to the near clip plane when setting the z position in ScreenToWorld() in order to avoid occasional clipping issues with the trails. And I moved the near frustum further back from the camera to make it easier to see in the scene view. Finally, a more advanced solution would be to use a separate camera just to render the trails. Good luck! And thank you samyam, great videos!
Heres how i fixed 2 problems: nullreference problem: If youre not using the camera that is automatically created when you create a scene, you cant use Camera.main unless you set the camera`s tag to MainCamera lines that are too small/ invisible problem: Camera must be set to Orthographic in the inspector
Hello, again thank you for the video, but after implementing the Touch input, I cannot trigger my button. In this case, the pause button. Could you please advice me on what to look for so that I can fix this?
Love your vids! Just so you know, when subscribing to the input action events, you don't need the lambda you have there - you can just subscribe the method directly (providing the signature is correct) This is a safer way to go since you can't unsubscribe anonymous assignments. Cheers!
2020.3.14f1 - I ended up getting miniscule distances in the 0.00 range between the two points. I found that using the raw position of "touchControls.Touch.PrimaryPosition.ReadValue();" in the events works vs. converting this using the ScreenToWorld methods. I'm not exactly sure why that's the case having followed every line you had but I may have missed something critical between this video and your New Input System Tutorial.
@samyam im trying to make it so that my character rotates when i swipe so should i use transform.Rotate or transform.rotation. and on start and end i get a null reference exception "object reference not set to an instance of an object" on swipedetection onenable and ondisable Plz help
Great tutorial. But somehow I stuck with the implementation of the swipe input. When I implement this script I cannot use my UI elements which had OnScreenButton script is on. I managed to track swipe start position and button rect over the screen and manage to call some scripts such as pause and options, but I stuck with the buttons which are rendered over another canvases. Is there any suggestion or best practices to use swipe input and buttons together?
You might have to check if there is a button in that area before starting the swipe in that case, you can probably use `EventSystem.current.IsPointerOverGameObject()` to detect it, and if there is a button then don't start the swipe. Is that what you meant?
If you get this error " You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings." then use this hack Project Settings > Player > Active Input Handling change it to both
I would actually advise against that since ideally you want your whole game to be using the new input system for consistency, so I would take the time and fix the parts in code where it’s using the old one (if possible).
I love your videos they are always helpful and informative, I would like to ask a question that I need help with, I used your tutorial for touch controls ( gears ) on the screen for movement and jump, when I add these input actions to that one, should I make them into one input map or separate them ?
Whatever works best for you! Typically you'd want to use different action maps when the player has to perform different actions in different areas, for example, having an action map for the UI, having an action map for underwater controls, having one for Land controls. You can also have more than one action map enabled at a time. Here's a video on action maps for more information: ua-cam.com/video/NZBAr_V7r0M/v-deo.html And thanks glad you like the videos!
@@samyam Thank you so much for answering my question! I will try that out. your videos are great I've been learning from them the past few months and they are incredible!
im using unity new input system .. for rotating camera we use delta mouse position but what will i do if i want to do the same thing for mobile ? if i use gamepad left stick it keeps rotating unless i put my finger off .. i could not find any delta stick for reading the change of value.. can you make a video on this topic
How can I make this more sensitive? It works fine but I want it to be very smooth to detect all the little swipes. Right now you kind of have to press hard to get it to work and sometimes it doesn't detect fast enough. Any Suggestion?
I got error that says: NullReferenceException: Object reference not set to an instance of an object SwipeDetection.OnDisable () (at Assets/Scripts/SwipeDetection.cs:27 My line at 27: inputManager.OnStartTouch += SwipeStart; Please Healp!
Hey, firstly: Awesome that you create this in-depth content for people out there!!! It's awesome to get information from somewhere! secondly: Sadly I find it hard to follow your video(s) as you keep throwing in references to other videos and tutorials, copy-pasting content in that cannot be followed nor understood by just following this video, and generally move at a pace and knowledge-level that is not suited for beginners. If such cross-references are made, I think it'd be great to have an actual series of consecutive tutorials to follow - if that is important. BIG Disclaimer here: To be fair, you do not at any point state that this WERE for beginners/intermediates!!! So feedback is from an somewhat unasked-for perspective maybe. I just feel this video makes a deep dive on a topic which I wish was covered at a more "beginner-friendly" level. to elaborate: I've been using the new input system for a while, made a number of gamepad and keyboard+mouse controllers with it. I would consider myself an advanced beginner in a sense. Or technically much less, watching your video, I guess?! But this video, while Ok in the beginning just starts to escalate in information-bombs and depth after a few minutes - quit frankly causing me to stop watching after importing that mysterious Singleton. Which is to bad (for me, of course), but I do not feel of having any benefit of copy pasting code en-masse without any clue what is happening anymore, nor following side-story-tutorials off topic. I am used to making all my controllers work with what feels much simpler and straight forward components? An InputActions, something that collects input, and then a script that can translate that input into actions. done. No singletons(?), no delegates, events, Utils-scripts, statics etc... Likely my C#-understanding is just WAY to nooby for this video?! :D I am happy so many people seemingly breeze through your tuts, and wish i was part of them, but maybe consider making a "beginner"/less optimized-version of this? PS: I really mean no offense or anything of the like. just a poor fool being way overwhelmed by your tutorial of an input manager I thought I understood comfortably well as a beginner.
Thanks for your comment and tips! Yes I agree I went pretty fast through the information at the time. In my latest videos I’ve set back the pace a bit and I actually redid one of the touch videos with a different format without using the singleton! ua-cam.com/video/4MOOitENQVg/v-deo.html Let me know if you have any thoughts, thanks! :)
If i understood correctly the new unity input system is suppose to make it easier to use for multiple input devices such as pc, phones, controllers. How would i go about say applying this swipe feature on say mouse input drag do i just add mouse touches in the setting? and if its controller input would i be able to just easily apply directional pads to determine if its left,right etc? without doing it the old fashion way using #regions to check specific inputs? Also thanks for the tutorial its not too fast or too slow yet its very informative ^^
Under the same action for Primary Contact you can put a mouse click and for Primary Position you can add in a mouse position and it would work on desktop with the same code. The controller joystick however is more of a delta and not a pure position, so you'd have to keep track of the current position on the screen and move it by the delta when the joystick is moved.
Heym just curious, which link in the description covers the ScreenPointToRay, I'm working on a 3d game and while using what was done in here ran into a problem, thanks for the help tho, this vide was very useful in me getting a good portion of my project knocked out
@@samyam thanks, that helps a lot, im also curious tho in if me not using the ScreenPointToRay could be causing my issue. Im working on making a Temple Run style game and the swipe controls worked fine until I started working with camera stuff, my initial thought is that the issue I'm having is being caused because the Utils is only using 2d space so when the camera turns it throws off what direction is getting registered but now I'm unsure cause I'm not 100% sure on how this code from the video you linked here could help fix that problem since its sending out a raycast to detect if its hitting something, sorry for the long question just trying to get this finished, also if there is another video you could link that could help with my issue (or if the code from this video actually does fix my issue and I'm just doing small brain) please let me know
If you are using screen to world coordinates it might be causing some issues since you need to pass in the correct depth to the z value of the vector you are passing in, you can try using ScreenPointToRay and see if it helps (make sure to backup your current progress!)
Could you help me understand, if a put my input manager as a singleton and i have multiplayer sort of speak, how will it effect it if it was singleton ?
Technically a tap should only be registered when the finger is lifted up from the screen under a certain time period so that shouldn’t happen (did you add the Tap interaction to the action?)
wait ok, so how do I actually put this swipe up and down to me the input I wanted to be. for example I have set up a script for jump. how do I jump while it detected swipe up, and crouch while it swipe down? Please help
Thanks! After a year I did change my method and now recommend the PlayerInput component as it comes with a lot of handy features/built-in functionality as I describe in this video :) ua-cam.com/video/m5WsmlEOFiA/v-deo.html
Hi... This is a great video... Can we use a small object as input controller instead of finger,mouse and game pad... What about detecting the coordinates of a physical object from touch screen...will it work?
This only works with Orthographic camera. Does anyone know how to chage the script to work with a perspective camera in a 3D scene? I would highly appreciate any guidance.
Seems to work for simulating touch input by mouse. But as soon as I use real touch (i have a touch display), the start position always is the last endposition. I don't know why. All I could do is skip a frame by delaying the OnStartEvent by 1 frame with a Coroutine (yield return null) before firing it. Works, but isn't very clean :/
Are you using touch from the Input Action Asset? If so try using the Enhanced Touch API to see if you have the same issue, or try upgrading the input system package
That’s a great Unity bug that they haven’t fixed 🥲 As a workaround you can use the EnhancedTouch API to get the touches or the first touch, example usage in the later part of the video here: ua-cam.com/video/ERAN5KBy2Gs/v-deo.html
Hi! Your Video is very helpful, but I am curious if I want to drag and drop an object with touch input. Is there anyway to let the object follow my touch?
Yep! On the touch down callback you can check if there is an object underneath, which I have a video for that: Get Object from Mouse Click and Call Functions through Interface - Unity Tutorial ua-cam.com/video/JID7YaHAtKA/v-deo.html Then if there is, you can start a coroutine and update the gameobject position to match the finger position (using ReadValue) (you can also lerp or smooth damp to the location if you want a nice effect), then cancel the coroutine once the finger is lifted up.
hey great video! how would i go about using this utils script with cinemachine? i know i can do m_lens.nearclipplane but how would i do ScreenTworoldPoint in this case? ty for any advice in advance
You can use the same function w/ Camera.main since it will be using the main camera either way (cinemachine just tells the main camera how to move with the Cinemachine Brain component)
I am still a beginner when it comes to scripting and game development and I faced a problem using your Singleton approach. It returns a null reference despite the DefaultExecutionOrder line. I made sure to follow your code step by step but I can't understand why I am getting this issue. To fix it, I simply declared a public static InputManager variable and set it on Awake.
Hm hard to say without seeing your code. You can also go to the Player Settings and change the order in the Script Execution Order category: docs.unity3d.com/Manual/class-MonoManager.html You can also join our Discord if you'd like and post the issue there with more detail: discord.gg/mj3dSnmaZc
I tried to combined your joystick Move and swipe up (Jump) together but now when I use joystick up direction my character jump too. Is there a way that can be stopped?
Your joystick should have it's own Move action, and you can make the swipe trigger only the jump action. Maybe you are accidentally combining the actions somehow?
can't get the near clipping plane working correctly, seems to only appear in the top left corner and as i move right it disappears into the distance, it's like the center is off by half a screen any thoughts?
Is this a 2D or 3D game? The camera near plane is just an easy way to bypass having to pass in the depth value each time to the screentoworldpoint function. Make sure your objects are on the same Z axis, if not they can disappear if you move the screen because the camera is cutting off certain parts of the view
@@samyam it's a 3d game, I figured out the zoom but can't use the clipping plane how would depth be handled if you can point me in the right direction, thanks for the great vids, most excellent job
@@samyam Wow! so your just not only the fastest typist on the planet but probably in my 35 years of programming the best I've ever seen, the deeper I get into your videos the more I want to pay you on a regular basis! Do you have a video covering mouse click hold and drag using the new system? oh wait Paul you just haven't found it yet! truly amazing! Thank you so much for responding to us lesser gods!
Thank you!! That’s a very nice comment :) Also, you can use the previous video as basis for clicking and dragging an object, once you click it in the interface then you can start a drag coroutine that will make an object follow your mouse (screentoworldpoint). Is that what you meant by dragging, or did you mean the camera?
Ah yes, you are correct :) My bad. But in some use cases you might need the positions for example if you need the player to swipe over an area, to make sure they are swiping over the rope you’d need the position of the finger. But if the delta works for you that’s good!
It’s not too complicated once you get a hang of it, it actually helps simplify code by making it event based rather than polling based. It’ll definitely help code structure in the long run!
@@samyam its hard to understand for beginner like me. I'll be back here when i got more advance skill and have a bigger project. But for now i will stick to other more simple tutorial.
This technique will act weird when multitouching though, as Primary Touch can switch from a finger to another. If you start dragging around with 1 finger, add a 2nd finger, then release the 1st one, the 2nd one will become primary and this will act like a very fast swipe. Is there a simple solution to that?
Couple of suggestions: 1) Try changing to Value instead of passthrough in the input action 2) Try binding specific fingers to input actions 3)Only do the swipe on the started callback 3)Hmm this may seem a bit unintuitive but you can possibly keep track in a dictionary what fingers you current have in the screen and their id, then remove from the dictionary if one of the fingers is lifted and if that finger is less the top count in the hash map then don’t perform a swipe with the remaining finger that’s now the primary (but not stored as so in the dictionary)
Hi, great video. Is there a way to prevent the swipe from occurring when interacting with UI elements? my swipe stops working when I'm pressing down on my on-screen mobile controls.
I have a list here on this video here: ua-cam.com/video/4WWX2_tZu5Q/v-deo.html ➡Debugger for Unity marketplace.visualstudio.com/items?itemName=Unity.unity-debug ➡Unity Tools marketplace.visualstudio.com/items?itemName=Tobiah.unity-tools ➡Unity Code Snippets marketplace.visualstudio.com/items?itemName=kleber-swf.unity-code-snippets ➡C# XML Documentation (Optional) marketplace.visualstudio.com/items?itemName=k--kato.docomment ➡GDScript Theme (Optional) marketplace.visualstudio.com/items?itemName=JamesSauer.gdscript-theme
Hello, @samyam. I loved your video a lot. Even as a beginner I understood most of the code with the way you're explaining. I'm using Unity 2021.3.20f1. And I'm getting the following errors (error CS0117, error CS1061) even after triple checking my code with your video guide. Basically, the errors suggest that Input Manager script doesn't contain a definition for Instance and also don't have definitions for 'OnStartTouch' and 'OnEndTouch'. What am I doing wrong? It would be of immense help ito solve this. I finished 5 levels of my game and decided to shift to the new input system and I'm struggling with this part. If this is fixed I have 25 new levels that I can implement and test. Thank you so much.
Hi, I had a similar problem and it was a spelling error for me: in the Singleton script, i had written var objs = FindObjectOfType(typeof(T)) as T[]; instead of: var objs = FindObjectsOfType(typeof(T)) as T[]; It's just one "s", but made all the difference for me. Hope this helps.
Hey! Lovely video! This has really helped us with touch controls! One small bug we're experiencing, and we see is also in your project, is that the first swipe upon running has a start point of (0,0) [A.K.A The bottom left of the screen] but every other swipe works fine. Does anyone know where this comes from? It seems to be an issue with the ReadValue(). Any help would be appreciated
I had that problem as well, I posted a bug on the forum but no one responded /: forum.unity.com/threads/first-position-of-touch-contact-is-0-0.1039135/
@@samyam Darn, still no replies, at least it has been reported now! Did you find any good hot-fix to ignore it? I'm thinking of just ignoring any input from 0,0 as it is unlikely anyone would touch there
@@samyam In the end I fixed it like this: If an input of 0,0 is detected then exit the method, but start a coroutine that waits one frame before calling "OnStartTouch" again, it seems to be fixed by the next frame
Здравстыуйте! Я переписывал код точь-в-точь, но мне пишет ошибку "Pointer should have exited all objects before being removed"((( Подскажите, пожалуйста, в чём может быть проблема?
Try changing the Pointer Behaviour in the Event System to All Pointers as Is, or try upgrading your input system package to a newer or preview version.
@@samyam Большое спасибо, помогло! И помимо этого, у меня была ошибка в синглтоне, где вместо "FindObjectsOfType()" я написал "FindObjectOfType()", без s. Вы самая лучшая, продолжайте в том же духе!)
The problem is I'm making a game were you have to swipe through the object from a certain angle(an opening in the object) and pass through the middle of it for it to cause an action to occur. If you draw a U shape around the object it counts as a straight line through it with a raycast, which would look weird when it does the action even though they never passed through the object. I would like to hear from someone more experienced how they would handle this problem. I'm tired right now and I will be going to sleep, but tomorrow I'm going to see if I can put a collision box on the trail and check if it passes though the object. If that is a bad idea and someone has a better idea please let me know.
Ok, so having a collider on the trail and object didn't work because it can't detect the collision if you swipe too fast which is really easy. I think I'm just going to use the enhanced touch api even though there will be a hit to performance. I don't really know if it is significant enough to make a difference, but I doubt it will be a problem and I don't know a better way to solve my problem.
Hey I'm making a game to put in my portfolio. I want to get a job in a small mobile game company. Should I use these scripts and write your name down in comments or should I invent all of these myself?
If you write the code it is yours, no need to put my name anywhere :) Anyways, this would only be a small part of your project, you still need the actual gameplay! Good luck!
Currently I don’t have a specific video on that but I have a playlist on the new input system and I do cover that in some of my videos Unity's New Input System 2020 ua-cam.com/play/PLKUARkaoYQT2nKuWy0mKwYURe2roBGJdr.html
@@samyam Actually i have Covered all your videos and You have done a fantastic job there. I was asking to that specific video because i had some issues when i was using that specific functionality and i moved Back to Old input system. Anyway, waiting for your new videos .Great job .
@@samyam basicaly , i want to rotate gameobject with touch and drag mechanics(on x axis ).so i was using delta (position) , so that gameobject rotate with certain value but the float value i got using delta is like(6.1,-12.2.-18.3,18.3) . I dont know the exact reason because i think i dont understand new input system fully yet and all tutorial i found on youtube are related to gamepad, keyboard, joystick(except your obviously). Thanks.
You can use delta for the direction, make sure you are converting to world coordinates, and then you can rotate the player around their y axis using that delta value normalized (just to get the direction)
Amazing tutorial Sam! I am learning so much from your tutorials :) I have some questions altough. Since we are making the swipes in the screen, why do we need to convert to world coordinates? I think is because of the Line Draw. But in my case I am only interested in the directions. Do I need to convert? I think that swipe direction in screen and world would be the same, don't they?
Am I the only one that thinks this is a massively convoluted way of such a simple thing as reading a swipe gesture?
I think the same jaajjajsj
So what is the easy and simple way you know ?
No you are not lol
For those who have the problem of the first start touch always return zero, the workaround is to delay the execution of StartTouchPrimary function in inputManager by 50ms for example
private async void StartTouchPrimary(InputAction.CallbackContext ctx)
{
await Task.Delay(50);
OnStartTouch?.Invoke(Utils.ScreenToWorld ...etc
}
(you can use coroutines or any other way for same thing)
(you can do that just for the first time)
This worked perfectly. Could you please elaborate the reason behind the bug itself? It will be helpful to know why this happens. Thanks.
Very strange, seems to work, not sure why, would also appreciate an explanation if anyone has one. Btw works with a delay of Task.Delay(1), just to reduce the delay further :)
I can see my new unfinished project already.
🤣
This is the only channel I watch at 0.5 speed.
I've been trying to slow down in more recent videos 😅
As usual, incredibly straight-forward and high quality tutorial! I'll definitely be talking about this next devlog, thank you so much for making these :)
Awesome tutorial, thank you. I like how you include most of the code made in other tutorials, so it is possible to understand everything by watching just one video.
Thank you!
Wow. The quality of this video tutorial is exceptional for UA-cam :) You are great !:)
Thank you so much!!
If you are watching this, you can also check the Example files from the Package Manager.
Input System have changes (1.5.1). There you can find a different way to do this.
Support touch, mouse, and pen, at the same time.
I will never be able to reach this person's level. I really wish I would one day have her alertness and professionalism in coding so I can at least keep up with this video with 1x speed
The best tutorials on Unity. Thank you so much. You are the best.
Thank you!
Don't worry, I've already found my mistake. thank you so much for the tutorial🥰
Best unity ambassador in UA-cam! thank you
Thanks! 😄
You have this breakeys vibes. I love the way you explain ❤ keep up the good work!
I feel grateful that I found out your channel today! This Input System playlist is fantastic! TY!
Could be the dopamine from my code actually working but, Samyam, you are the most amazing human alive. Thank you !
I’ll take it 😂 Congrats 🎉
Spend three days in learning a tweenty-five minutes tutorial.Still believe I can become a game developer.
You definitely can! Just keep going 😄
You don't need to use two delegates, since delegates work sort of like templates, the actual functionality is subscribed to the event.
If somebody is struggling with a bug that the very first start position is on the left bottom corner, I have found I guess the easiest solution.
In the Input Action window, you need to create one additional action for example 'PrimaryStartPosition' with a binding Touchscreen>Primary Position>Start Position. This one works correctly even with the very first touch. It is a start position of touch, so in code in the InputManager you have to change a function StartTouchPrimary. Basically, you just need to swap playerControls.Touch.PrimaryStartPosition.ReadValue() with playerControls.Touch.PrimaryStartPosition.ReadValue().
Hope it will be helpful for somebody 😅
here from the third link on bing lol, instantly subbed, hoping to learn more
Thanks a a lot, I really appreciate your detailed tutorials about new Input System. Hope you upload more of those. Cheers...
Thanks!
I was using this tutorial to help me out with my final project, struggled for hours trying to figure out why my touches were stuck in the center of the screen and my debug lines were tiny... your canvas distance needs to be the same as your near clip plane. my group members moved it and I didn't know lol
I love your easy descriptions and explanation, buy as someone whose had his issue w/ C# (and Unity) respectively, your need to slow down girl lol.
Haha I agree the video was a while ago, hopefully my newer videos are much easier to follow :)
I love your tutorials! They are helping me a lot at my job. Also, you sound like Robin from Stranger Things and she is so nice. So are you : )
I like you when you say fast "ALRIGHT"
Thanks for the video. To make it easier I used an extension method on the camera class to convert the coordinates.
Your tutorials are really helpful! 🙏
Thank you!
You are awesome, thanks for the tutorial!
Thank you I was just looking for this.
It works, but when you reload the scene before you end the swipe it makes a NullReferenceException. It still works, nothing breaks, and i think the game doesn`t crash.
GOOD Place to learn Essentials of Unity...Good Programmer...Love u Kid...Voice seems Kid but sweet
Nice implementation👍
Also, anyone know why on the first swipe, the startPosition is always the bottom left position of the canvas? Seems to be the case for @samyam as well here 14:30 on the first line drawn, you can see it starts from the bottom left, even though thats not where she clicks. Any ideas why?
hi, i have trouble with the first touch always register wrong. any clue where there problem is?
Thanks for the great vid, keep it up!
Could you do a vid on how to implement a two-finger zoom/rotation gesture recognition, would much appreciate!
Yes!
At 14:25, it almost looks like you illustrate your point using a different script (different InputManager) than the one you had been referencing/writing throughout the tutorial beforehand. This admittedly makes it pretty hard to follow, any advice if we're hitting errors here? (For me, no Debug.Drawlines are showing up in my editor when I play.)
Unfortunately, I have the same issue and am not sure how to fix this.
So it's been about 10 months since you asked this question. I hope you found an answer by now, but for those who may be facing a similar issue:
The issue may well be related to the camera frustum. In the scene view click on your camera. You should see a pyramid shaped outline with the point near your camera. That's the frustum. The ScreenToWorld() method in samyams's video causes the lines and trail to be rendered at the very tip of the frustum nearest the camera. You may have to zoom in on that small portion of the screen to see the lines and trail.
There are a few ways to change the behavior. You can move the near clipping plane away from the camera using the camera's inspector. Note that nothing closer to the camera than the near clip plane will be rendered.
You can also change ScreenToWorld() to draw the lines at any arbitrary z-depth deeper than the near clipping plane. Note that if you do you may find the trails appear to go through or behind objects in your scene.
I did both in my test scene, I had to add a small amount (0.1) to the near clip plane when setting the z position in ScreenToWorld() in order to avoid occasional clipping issues with the trails. And I moved the near frustum further back from the camera to make it easier to see in the scene view.
Finally, a more advanced solution would be to use a separate camera just to render the trails.
Good luck! And thank you samyam, great videos!
Heres how i fixed 2 problems:
nullreference problem: If youre not using the camera that is automatically created when you create a scene, you cant use Camera.main unless you set the camera`s tag to MainCamera
lines that are too small/ invisible problem: Camera must be set to Orthographic in the inspector
Thanks for mentioning!
You sir is a life saver! Thanks for the tip about setting the camera to Orthographic!
Great Tutorial! thank you!
Thanks for your videos.
I Appreciate you!
Thank you!
muchas gracias tienes una linda voz y explicas muy bien todo ☺♥
gracias! :)
Hello, again thank you for the video, but after implementing the Touch input, I cannot trigger my button. In this case, the pause button. Could you please advice me on what to look for so that I can fix this?
Love your vids!
Just so you know, when subscribing to the input action events, you don't need the lambda you have there - you can just subscribe the method directly (providing the signature is correct)
This is a safer way to go since you can't unsubscribe anonymous assignments.
Cheers!
Good point! I tend to forget that, will keep in mind thanks 🙂
@@samyam I love the input system - so intuitive and flexible.
Thanks again for your vids, they're awesome!
This may never get answered, but on the off chance it does, does this work with the tutorial for touch controls that you made in November of 2022?
October 2024 - All working!
2020.3.14f1 - I ended up getting miniscule distances in the 0.00 range between the two points. I found that using the raw position of "touchControls.Touch.PrimaryPosition.ReadValue();" in the events works vs. converting this using the ScreenToWorld methods. I'm not exactly sure why that's the case having followed every line you had but I may have missed something critical between this video and your New Input System Tutorial.
Hm that is strange. Do you mean between the previous and current position it was as if it didn’t move (minuscule distance between them)?
cool ^^
@samyam im trying to make it so that my character rotates when i swipe so should i use transform.Rotate or transform.rotation. and on start and end i get a null reference exception "object reference not set to an instance of an object" on swipedetection onenable and ondisable
Plz help
Great tutorial. But somehow I stuck with the implementation of the swipe input. When I implement this script I cannot use my UI elements which had OnScreenButton script is on. I managed to track swipe start position and button rect over the screen and manage to call some scripts such as pause and options, but I stuck with the buttons which are rendered over another canvases. Is there any suggestion or best practices to use swipe input and buttons together?
You might have to check if there is a button in that area before starting the swipe in that case, you can probably use `EventSystem.current.IsPointerOverGameObject()` to detect it, and if there is a button then don't start the swipe. Is that what you meant?
Yeap thats exactly what I mean. But I'm not really sure where to implement this in new input system.
If you get this error " You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings."
then use this hack
Project Settings > Player > Active Input Handling change it to both
I would actually advise against that since ideally you want your whole game to be using the new input system for consistency, so I would take the time and fix the parts in code where it’s using the old one (if possible).
I love your videos they are always helpful and informative, I would like to ask a question that I need help with, I used your tutorial for touch controls ( gears ) on the screen for movement and jump, when I add these input actions to that one, should I make them into one input map or separate them ?
Whatever works best for you! Typically you'd want to use different action maps when the player has to perform different actions in different areas, for example, having an action map for the UI, having an action map for underwater controls, having one for Land controls. You can also have more than one action map enabled at a time. Here's a video on action maps for more information: ua-cam.com/video/NZBAr_V7r0M/v-deo.html
And thanks glad you like the videos!
@@samyam Thank you so much for answering my question! I will try that out. your videos are great I've been learning from them the past few months and they are incredible!
Awesome glad you like them! 😁
im using unity new input system .. for rotating camera we use delta mouse position but what will i do if i want to do the same thing for mobile ? if i use gamepad left stick it keeps rotating unless i put my finger off .. i could not find any delta stick for reading the change of value.. can you make a video on this topic
Why does the first line always start at the bottom left corner of the camera?
That’s a Unity Input System bug, try either upgrading the input system package or using the enhanced touch api as a workaround.
How can I make this more sensitive? It works fine but I want it to be very smooth to detect all the little swipes. Right now you kind of have to press hard to get it to work and sometimes it doesn't detect fast enough. Any Suggestion?
I got error that says: NullReferenceException: Object reference not set to an instance of an object SwipeDetection.OnDisable () (at Assets/Scripts/SwipeDetection.cs:27
My line at 27:
inputManager.OnStartTouch += SwipeStart;
Please Healp!
I have an error: CS0246 PlayerControls could not be found, how can I change it ?
Hey,
firstly: Awesome that you create this in-depth content for people out there!!! It's awesome to get information from somewhere!
secondly: Sadly I find it hard to follow your video(s) as you keep throwing in references to other videos and tutorials, copy-pasting content in that cannot be followed nor understood by just following this video, and generally move at a pace and knowledge-level that is not suited for beginners. If such cross-references are made, I think it'd be great to have an actual series of consecutive tutorials to follow - if that is important.
BIG Disclaimer here: To be fair, you do not at any point state that this WERE for beginners/intermediates!!! So feedback is from an somewhat unasked-for perspective maybe.
I just feel this video makes a deep dive on a topic which I wish was covered at a more "beginner-friendly" level.
to elaborate:
I've been using the new input system for a while, made a number of gamepad and keyboard+mouse controllers with it. I would consider myself an advanced beginner in a sense. Or technically much less, watching your video, I guess?! But this video, while Ok in the beginning just starts to escalate in information-bombs and depth after a few minutes - quit frankly causing me to stop watching after importing that mysterious Singleton. Which is to bad (for me, of course), but I do not feel of having any benefit of copy pasting code en-masse without any clue what is happening anymore, nor following side-story-tutorials off topic.
I am used to making all my controllers work with what feels much simpler and straight forward components? An InputActions, something that collects input, and then a script that can translate that input into actions. done. No singletons(?), no delegates, events, Utils-scripts, statics etc... Likely my C#-understanding is just WAY to nooby for this video?! :D
I am happy so many people seemingly breeze through your tuts, and wish i was part of them, but maybe consider making a "beginner"/less optimized-version of this?
PS: I really mean no offense or anything of the like. just a poor fool being way overwhelmed by your tutorial of an input manager I thought I understood comfortably well as a beginner.
Thanks for your comment and tips! Yes I agree I went pretty fast through the information at the time. In my latest videos I’ve set back the pace a bit and I actually redid one of the touch videos with a different format without using the singleton! ua-cam.com/video/4MOOitENQVg/v-deo.html
Let me know if you have any thoughts, thanks! :)
@@samyam Thank you, I will check it out :)
If i understood correctly the new unity input system is suppose to make it easier to use for multiple input devices such as pc, phones, controllers. How would i go about say applying this swipe feature on say mouse input drag do i just add mouse touches in the setting? and if its controller input would i be able to just easily apply directional pads to determine if its left,right etc? without doing it the old fashion way using #regions to check specific inputs?
Also thanks for the tutorial its not too fast or too slow yet its very informative ^^
Under the same action for Primary Contact you can put a mouse click and for Primary Position you can add in a mouse position and it would work on desktop with the same code. The controller joystick however is more of a delta and not a pure position, so you'd have to keep track of the current position on the screen and move it by the delta when the joystick is moved.
Thank you!
Heym just curious, which link in the description covers the ScreenPointToRay, I'm working on a 3d game and while using what was done in here ran into a problem, thanks for the help tho, this vide was very useful in me getting a good portion of my project knocked out
Here ya go :) Good luck!
ua-cam.com/video/JID7YaHAtKA/v-deo.html
@@samyam thanks, that helps a lot, im also curious tho in if me not using the ScreenPointToRay could be causing my issue. Im working on making a Temple Run style game and the swipe controls worked fine until I started working with camera stuff, my initial thought is that the issue I'm having is being caused because the Utils is only using 2d space so when the camera turns it throws off what direction is getting registered but now I'm unsure cause I'm not 100% sure on how this code from the video you linked here could help fix that problem since its sending out a raycast to detect if its hitting something, sorry for the long question just trying to get this finished, also if there is another video you could link that could help with my issue (or if the code from this video actually does fix my issue and I'm just doing small brain) please let me know
If you are using screen to world coordinates it might be causing some issues since you need to pass in the correct depth to the z value of the vector you are passing in, you can try using ScreenPointToRay and see if it helps (make sure to backup your current progress!)
this broke my primary touch/tab [Touchscreen] input. how can I have both working?
Could you help me understand, if a put my input manager as a singleton and i have multiplayer sort of speak, how will it effect it if it was singleton ?
Hey, how can I have a tap isolated from the swipe?
I want to detect taps and swipes but when I do a swipe it naturally captures a tap
Technically a tap should only be registered when the finger is lifted up from the screen under a certain time period so that shouldn’t happen (did you add the Tap interaction to the action?)
wait ok, so how do I actually put this swipe up and down to me the input I wanted to be. for example I have set up a script for jump. how do I jump while it detected swipe up, and crouch while it swipe down? Please help
Your tutorials on the Input System are awesome.
I was wondering, any reason why you don't use the Player Input component?
Thanks! After a year I did change my method and now recommend the PlayerInput component as it comes with a lot of handy features/built-in functionality as I describe in this video :)
ua-cam.com/video/m5WsmlEOFiA/v-deo.html
Hi... This is a great video... Can we use a small object as input controller instead of finger,mouse and game pad... What about detecting the coordinates of a physical object from touch screen...will it work?
Is this will work in 3d game if it will it require any changes in scripts or not
Yeah it’ll work!
Could this possibly work if I build this with WebGL and try using it in a mobile browser?
It is not nice after importing a file which is not in the project in the middle of the video which lets the audience nothing to do more
how can i do that in a bound eg in a recttransform or any bound
This only works with Orthographic camera. Does anyone know how to chage the script to work with a perspective camera in a 3D scene? I would highly appreciate any guidance.
It does work for perspective camera as well.
you have to change the method in the utils
Seems to work for simulating touch input by mouse. But as soon as I use real touch (i have a touch display), the start position always is the last endposition. I don't know why. All I could do is skip a frame by delaying the OnStartEvent by 1 frame with a Coroutine (yield return null) before firing it. Works, but isn't very clean :/
Are you using touch from the Input Action Asset? If so try using the Enhanced Touch API to see if you have the same issue, or try upgrading the input system package
Click clack! Kind of off-topic question - what keyboard/switches are you using?
logitech g815 blue clicky!
At 7:00 what's the full 3D version for camera.ScreenPointToRay()?
Example Usage:
docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html
Hi, for the first swipe the start position of swipe is the left lower position of near clip . What’s wrong? Later swipes it works fine.
That’s a great Unity bug that they haven’t fixed 🥲 As a workaround you can use the EnhancedTouch API to get the touches or the first touch, example usage in the later part of the video here:
ua-cam.com/video/ERAN5KBy2Gs/v-deo.html
Hi! Your Video is very helpful, but I am curious if I want to drag and drop an object with touch input. Is there anyway to let the object follow my touch?
Yep! On the touch down callback you can check if there is an object underneath, which I have a video for that:
Get Object from Mouse Click and Call Functions through Interface - Unity Tutorial
ua-cam.com/video/JID7YaHAtKA/v-deo.html
Then if there is, you can start a coroutine and update the gameobject position to match the finger position (using ReadValue) (you can also lerp or smooth damp to the location if you want a nice effect), then cancel the coroutine once the finger is lifted up.
hey great video! how would i go about using this utils script with cinemachine? i know i can do m_lens.nearclipplane but how would i do ScreenTworoldPoint in this case? ty for any advice in advance
You can use the same function w/ Camera.main since it will be using the main camera either way (cinemachine just tells the main camera how to move with the Cinemachine Brain component)
I am still a beginner when it comes to scripting and game development and I faced a problem using your Singleton approach. It returns a null reference despite the DefaultExecutionOrder line. I made sure to follow your code step by step but I can't understand why I am getting this issue. To fix it, I simply declared a public static InputManager variable and set it on Awake.
Hm hard to say without seeing your code. You can also go to the Player Settings and change the order in the Script Execution Order category:
docs.unity3d.com/Manual/class-MonoManager.html
You can also join our Discord if you'd like and post the issue there with more detail:
discord.gg/mj3dSnmaZc
Спасибо!
Thank you!!! :D
Thank would be helpful 🙂 btw
Which snippets you use for vs code pliss tell
marketplace.visualstudio.com/items?itemName=kleber-swf.unity-code-snippets
@@samyam Can you do like a visual studio code unity setup with the all the packages you use and stuff?
I have one here ua-cam.com/video/4WWX2_tZu5Q/v-deo.html
there are no mistakes, but nothing happens in my scene at all, why?
I tried to combined your joystick Move and swipe up (Jump) together but now when I use joystick up direction my character jump too. Is there a way that can be stopped?
Your joystick should have it's own Move action, and you can make the swipe trigger only the jump action. Maybe you are accidentally combining the actions somehow?
Thank you for the great tutorial! How to adapt it to 3d game?
You can read the swipe data to do anything you want in a 3d game, what are you trying to accomplish?
can't get the near clipping plane working correctly, seems to only appear in the top left corner and as i move right it disappears into the distance, it's like the center is off by half a screen any thoughts?
Is this a 2D or 3D game? The camera near plane is just an easy way to bypass having to pass in the depth value each time to the screentoworldpoint function. Make sure your objects are on the same Z axis, if not they can disappear if you move the screen because the camera is cutting off certain parts of the view
@@samyam it's a 3d game, I figured out the zoom but can't use the clipping plane how would depth be handled if you can point me in the right direction, thanks for the great vids, most excellent job
This video on selecting an object might help you out :)
ua-cam.com/video/JID7YaHAtKA/v-deo.html
@@samyam Wow! so your just not only the fastest typist on the planet but probably in my 35 years of programming the best I've ever seen, the deeper I get into your videos the more I want to pay you on a regular basis!
Do you have a video covering mouse click hold and drag using the new system? oh wait Paul you just haven't found it yet! truly amazing!
Thank you so much for responding to us lesser gods!
Thank you!! That’s a very nice comment :)
Also, you can use the previous video as basis for clicking and dragging an object, once you click it in the interface then you can start a drag coroutine that will make an object follow your mouse (screentoworldpoint). Is that what you meant by dragging, or did you mean the camera?
@samyam nice tutorial but there is a better way by getting the delta and see if its a bigger than a certain value
Thanks! Yes you can do that but then you’d still need a way to track the direction of the swipe
@@samyam Hi, the delta returns a vector 2 of an x and y you can check if delta.x >= 35 or if delta.x
Ah yes, you are correct :) My bad. But in some use cases you might need the positions for example if you need the player to swipe over an area, to make sure they are swiping over the rope you’d need the position of the finger. But if the delta works for you that’s good!
I just want to make simple swipe control, why this new input system looks more complicated than the old one
It’s not too complicated once you get a hang of it, it actually helps simplify code by making it event based rather than polling based. It’ll definitely help code structure in the long run!
@@samyam its hard to understand for beginner like me. I'll be back here when i got more advance skill and have a bigger project. But for now i will stick to other more simple tutorial.
I have a simpler video on the input system which is more introductory if you’d like:
ua-cam.com/video/yRI44aYLDQs/v-deo.html
This technique will act weird when multitouching though, as Primary Touch can switch from a finger to another. If you start dragging around with 1 finger, add a 2nd finger, then release the 1st one, the 2nd one will become primary and this will act like a very fast swipe. Is there a simple solution to that?
Couple of suggestions:
1) Try changing to Value instead of passthrough in the input action
2) Try binding specific fingers to input actions
3)Only do the swipe on the started callback
3)Hmm this may seem a bit unintuitive but you can possibly keep track in a dictionary what fingers you current have in the screen and their id, then remove from the dictionary if one of the fingers is lifted and if that finger is less the top count in the hash map then don’t perform a swipe with the remaining finger that’s now the primary (but not stored as so in the dictionary)
Hi, great video. Is there a way to prevent the swipe from occurring when interacting with UI elements? my swipe stops working when I'm pressing down on my on-screen mobile controls.
Have you ever founbd what the issue was? im facing the same problem :/
what extensions for vscode do you use?
I have a list here on this video here: ua-cam.com/video/4WWX2_tZu5Q/v-deo.html
➡Debugger for Unity
marketplace.visualstudio.com/items?itemName=Unity.unity-debug
➡Unity Tools
marketplace.visualstudio.com/items?itemName=Tobiah.unity-tools
➡Unity Code Snippets
marketplace.visualstudio.com/items?itemName=kleber-swf.unity-code-snippets
➡C# XML Documentation (Optional)
marketplace.visualstudio.com/items?itemName=k--kato.docomment
➡GDScript Theme (Optional)
marketplace.visualstudio.com/items?itemName=JamesSauer.gdscript-theme
Hello, @samyam.
I loved your video a lot. Even as a beginner I understood most of the code with the way you're explaining. I'm using Unity 2021.3.20f1. And I'm getting the following errors (error CS0117, error CS1061) even after triple checking my code with your video guide. Basically, the errors suggest that Input Manager script doesn't contain a definition for Instance and also don't have definitions for 'OnStartTouch' and 'OnEndTouch'. What am I doing wrong? It would be of immense help ito solve this. I finished 5 levels of my game and decided to shift to the new input system and I'm struggling with this part. If this is fixed I have 25 new levels that I can implement and test. Thank you so much.
Hi, I had a similar problem and it was a spelling error for me: in the Singleton script, i had written
var objs = FindObjectOfType(typeof(T)) as T[];
instead of:
var objs = FindObjectsOfType(typeof(T)) as T[];
It's just one "s", but made all the difference for me.
Hope this helps.
Hey! Lovely video! This has really helped us with touch controls! One small bug we're experiencing, and we see is also in your project, is that the first swipe upon running has a start point of (0,0) [A.K.A The bottom left of the screen] but every other swipe works fine. Does anyone know where this comes from? It seems to be an issue with the ReadValue(). Any help would be appreciated
I had that problem as well, I posted a bug on the forum but no one responded /:
forum.unity.com/threads/first-position-of-touch-contact-is-0-0.1039135/
@@samyam Darn, still no replies, at least it has been reported now! Did you find any good hot-fix to ignore it? I'm thinking of just ignoring any input from 0,0 as it is unlikely anyone would touch there
Yeah you can ignore the first touch or do it that way, i like your way better!
@@samyam In the end I fixed it like this:
If an input of 0,0 is detected then exit the method, but start a coroutine that waits one frame before calling "OnStartTouch" again, it seems to be fixed by the next frame
@@MrMartyn4700 thanks mate! fix works for me and saved me hours of debugging
how can i get the singleton?
Write it
Singleton doesn't work for me :(
Do you have any errors in the console?
you could also write PrimaryContact.started += StartTouchPrimary; instead of lambda :)
God bless you
Здравстыуйте! Я переписывал код точь-в-точь, но мне пишет ошибку "Pointer should have exited all objects before being removed"((( Подскажите, пожалуйста, в чём может быть проблема?
Try changing the Pointer Behaviour in the Event System to All Pointers as Is, or try upgrading your input system package to a newer or preview version.
@@samyam Большое спасибо, помогло! И помимо этого, у меня была ошибка в синглтоне, где вместо "FindObjectsOfType()" я написал "FindObjectOfType()", без s. Вы самая лучшая, продолжайте в том же духе!)
@@epicdayman6200 Thank you!! :)
The problem is I'm making a game were you have to swipe through the object from a certain angle(an opening in the object) and pass through the middle of it for it to cause an action to occur. If you draw a U shape around the object it counts as a straight line through it with a raycast, which would look weird when it does the action even though they never passed through the object. I would like to hear from someone more experienced how they would handle this problem. I'm tired right now and I will be going to sleep, but tomorrow I'm going to see if I can put a collision box on the trail and check if it passes though the object. If that is a bad idea and someone has a better idea please let me know.
Ok, so having a collider on the trail and object didn't work because it can't detect the collision if you swipe too fast which is really easy. I think I'm just going to use the enhanced touch api even though there will be a hit to performance. I don't really know if it is significant enough to make a difference, but I doubt it will be a problem and I don't know a better way to solve my problem.
perfect tutorial, i thought it would be Action Type = Swipe Control Vector2 :((( but no
Hey I'm making a game to put in my portfolio. I want to get a job in a small mobile game company. Should I use these scripts and write your name down in comments or should I invent all of these myself?
If you write the code it is yours, no need to put my name anywhere :) Anyways, this would only be a small part of your project, you still need the actual gameplay! Good luck!
@@samyam :D Thank you. Good luck to you too.
can you Plz make a video on touch/ delta position using New input system?
Currently I don’t have a specific video on that but I have a playlist on the new input system and I do cover that in some of my videos
Unity's New Input System 2020
ua-cam.com/play/PLKUARkaoYQT2nKuWy0mKwYURe2roBGJdr.html
@@samyam Actually i have Covered all your videos and You have done a fantastic job there. I was asking to that specific video because i had some issues when i was using that specific functionality and i moved Back to Old input system. Anyway, waiting for your new videos .Great job .
Thanks! What would you like to specifically know about the touch/delta position?
@@samyam basicaly , i want to rotate gameobject with touch and drag mechanics(on x axis ).so i was using delta (position) , so that gameobject rotate with certain value but the float value i got using delta is like(6.1,-12.2.-18.3,18.3) . I dont know the exact reason because i think i dont understand new input system fully yet and all tutorial i found on youtube are related to gamepad, keyboard, joystick(except your obviously). Thanks.
You can use delta for the direction, make sure you are converting to world coordinates, and then you can rotate the player around their y axis using that delta value normalized (just to get the direction)
Amazing tutorial Sam! I am learning so much from your tutorials :)
I have some questions altough. Since we are making the swipes in the screen, why do we need to convert to world coordinates?
I think is because of the Line Draw. But in my case I am only interested in the directions. Do I need to convert?
I think that swipe direction in screen and world would be the same, don't they?
Yeah that works! You can use either in your case if you don't need to use world coordinates :)
@@samyam Ok! Thanks a lot :)
What is the VS theme?
Godot theme!