A Better Way To Manage Collision in Unity (For Beginners)

Поділитися
Вставка
  • Опубліковано 2 лют 2025

КОМЕНТАРІ • 123

  • @LostRelicGames
    @LostRelicGames  4 роки тому +9

    If you are interested in making platformers, this is a fantastic starting point - u3d.as/2eYe (made by me)

  • @bradleywood1984
    @bradleywood1984 Рік тому +2

    I've only just recently began my game development journey after 20 years in a technical space concerning metrology. I find your videos to be down to Earth and easy to grasp. I love the simplicity here with centralizing the processing of collisions. Good work. Can't wait for Blood & Mead!

  • @LostRelicGames
    @LostRelicGames  4 роки тому +14

    Note: This video is designed for beginners to Unity and coding principles like D.R.Y. The knowledge might seem rudimentary to seasoned developers, but serves the purpose of giving newcomers an alternative way to think about code logic flow.

    • @gregoryhoward7594
      @gregoryhoward7594 4 роки тому +1

      They need to use EXACTLY this in the big games like Madden because they are horrendous with screwing up their code and it is obvious they don't reuse code like they should.

  • @valairan
    @valairan 4 роки тому +25

    Why doesn’t this guy have more subscribers?

    • @DesnesCitrus
      @DesnesCitrus 4 роки тому +9

      Lean back and watch him grow. He will be big if He is keep making good stuff like this.

    • @NStripleseven
      @NStripleseven 4 роки тому +1

      I don't know, but just you wait, I'm sure he'll get more in the near future.

    • @beri4138
      @beri4138 4 роки тому +2

      He went from 10k to 20k in a blink of an eye

  • @Chexmix6
    @Chexmix6 3 роки тому +1

    Thank you! I was having SO much trouble on how to check what collision is being detected, and I couldn't find anything to help me until I found this!

  • @marcmoran9380
    @marcmoran9380 4 роки тому +4

    Keep these awesome videos coming - unfortunately I haven't had anytime to work on any fun projects, but I love watching these very clear and concise tutorials.

  • @sneeky_09
    @sneeky_09 4 роки тому +6

    Thank you for these tutorials, you really help to make things "click"! I have on and off done programming for a long time, but not in game design and I just couldn't get my head round how to avoid repeating code for collisions, it seems obvious now! thanks again

  • @smallgaming8601
    @smallgaming8601 4 роки тому +48

    Hmm, this tip is kind of standard programming practice. Like the principle “Don´t Repeat Yourself” and eliminating duplicate code. Still a good tip for beginners.

    • @HandyAndyG
      @HandyAndyG 4 роки тому +5

      Exactly !!! I don't get it, this is simple and standard practice in coding. Why is everyone else commenting as though he has just produced UA-cam Gold?

    • @LostRelicGames
      @LostRelicGames  4 роки тому +21

      For sure, although the obvious is not always so obvious when starting out. Many of these concepts are foreign. I edited the title to add 'beginner' for clarity

    • @smallgaming8601
      @smallgaming8601 4 роки тому +2

      @@LostRelicGames that is good for managing the expectations of your viewers👍 Keep on making good videos.

    • @LostRelicGames
      @LostRelicGames  4 роки тому +23

      ​@@HandyAndyG You make the bold assumption that everyone else watching this video has your knowledge. Realize that most people coming to Unity are not CS graduates, but are often hobbyists , non-coders & artists with no foundational programming skills.

    • @qqq9542
      @qqq9542 4 роки тому +2

      @@LostRelicGames Very true. I didnt know about this tip so thank you, LRG. And screw that guy for being a know-it-all. This video was very helpful.

  • @theplaymakerno1
    @theplaymakerno1 4 роки тому +21

    You should start in Star Wars! Perfect look for a Jedi!

    • @beri4138
      @beri4138 4 роки тому +3

      No no no he should star in John Wick 4

    • @josemaquille5469
      @josemaquille5469 3 роки тому

      Yeah i always think of the jedi in the first part idk his name anymore ( the master of obi wan)

  • @willpetillo1189
    @willpetillo1189 4 роки тому +14

    An alternative technique in this case is to use something like this:
    OnCollisionEnter(Collision other) { OnTriggerEnter(other.collider) }
    OnTriggerEnter(Collider other) { /* your code here */ }
    That way, if additional behaviors are later needed that don't fit into the concept of "ProcessCollision", you still only need to change one thing. Also, it's more explicit in the point that: "For this class, handle collisions *exactly the same* as triggers", rather than having to read two methods and notice that they call the function.

    • @himanshugupta325
      @himanshugupta325 4 роки тому +1

      I don't know how to thank you, you helped me a lot.

    • @pliniomourao
      @pliniomourao 3 роки тому

      Coherence analysis. I love it.
      thank you for sharing this.

  • @berkalkan3382
    @berkalkan3382 4 роки тому +2

    this channel is so underrated

  • @TheFRBublitz
    @TheFRBublitz 2 роки тому

    glad to see that zlatan is exploring his talent in game development aswell. He was pretty good playing football

  • @dukewendel
    @dukewendel 2 роки тому +4

    The next step would be to move the collision detection to its own script and use events, that way you separate the logic from the callback making it even cleaner :)

  • @JoaoNeto-up8zi
    @JoaoNeto-up8zi 2 роки тому

    You deserve a prize for this, that's some sharp headspace saving simplification, well done man

  • @HyBlock
    @HyBlock 4 роки тому +11

    comparing tags for everything is also a bad way to go about it, especially if you have a complex game. If you truly want to 'centralise' everything then make an IDamageable interface so your code looks cleaner :)

    • @georsonchua
      @georsonchua 4 роки тому +2

      what is "IDamageable interface"?

    • @LostRelicGames
      @LostRelicGames  4 роки тому +13

      Hi Edge, thanks for the comment. I'm primarily targeting beginners with these tutorials. Interfaces are beyond the scope of this lesson, but i'll most certainly cover them in the future.

    • @pliniomourao
      @pliniomourao 3 роки тому

      @@LostRelicGames You could address some patterns for good practices. in your video it reminds me of "Single-responsibility principle". I believe speaking of patterns in this situations is a good way to enforce good practices and gives a knowledge for a more clean code. And even this kind of pattern can be associated for beginners.

  • @tauheedgamedev2388
    @tauheedgamedev2388 4 роки тому

    Nice Basics tutorial. Good luck with the Asset

  • @derlinjesustaverasperalta1724
    @derlinjesustaverasperalta1724 3 роки тому

    Omg , 😲 knowledge acquired, wrote twice the code. Now i know thanks :)

  • @Xgamesvidoes
    @Xgamesvidoes 4 роки тому

    The simple little things can clean up a lot!
    Nice video!

  • @gabrielsouza9651
    @gabrielsouza9651 2 роки тому

    Very interesting concept. This centralizing systems could help a lot in every situation in coding since almost every project needs a serie of collisions methods. Thanks it was a nice video!

  • @dardilac
    @dardilac 4 роки тому

    Pretty nice tutotial I must say. I never figured out that. This will help a lot in the future

  • @limqueenyt
    @limqueenyt 2 роки тому

    Thank you very muchhh!! This totally solve my questions!

  • @izz3878
    @izz3878 3 роки тому

    Thank you for sharing your knowledge !

  • @V.Z.69
    @V.Z.69 Місяць тому

    Would you say that this is the next BEST thing since Adobe Flash AS3? I really miss game coding with Flash, especially the Movie objects and Layers was so easy to get animation. It was the best. Whatever Google Government and their shills have to say about it, it was indeed the BEST for game dev.

  • @deadbroadcastpc
    @deadbroadcastpc 4 роки тому

    Very useful John! Always appreciate the tips!

  • @Hersonrock12
    @Hersonrock12 2 роки тому

    Great tip! I saved it on my notes :)

  • @THEspindoctor84
    @THEspindoctor84 3 роки тому

    this is pretty straightforward, but for some reason I also have not implemented it! thanks for the tip!

  • @Zegamis
    @Zegamis 2 роки тому

    Awesome Video. Thanks for the help.

  • @divyampachkawade850
    @divyampachkawade850 3 роки тому

    Thank You Very Much You Video Helped Me A Lot

  • @glenmartin9974
    @glenmartin9974 4 роки тому

    This is soo "DRY"... I like it!

  • @creesee777
    @creesee777 4 роки тому

    John Wick makes the best tutorials.

  • @kingdom216
    @kingdom216 3 роки тому

    I need to set a game object after colliding with a trigger, like a puck to a face off circle after colliding with a goal trigger and different face off circles after colliding with boundary triggers

  • @chesterapavliashvili1533
    @chesterapavliashvili1533 4 роки тому

    Love to hear nice mecha keyboard sounds :D
    I like your tutorials pretty much, good work and keep it up

  • @oleksiistetsenko6028
    @oleksiistetsenko6028 3 роки тому

    i misheard "in this video i wanna shave with you" XD
    p.s. Thank you for tutorial o/

  • @robertjunior5272
    @robertjunior5272 3 роки тому

    Very helpful and awesome

  • @watchmecode5239
    @watchmecode5239 4 роки тому +1

    Nice workflow. "It`s good to stay organized". It would be really nice a tutorial on scripts for interactable objects. This could be quite confusing and the material out there is not that simple or well explained. Thanks for sharing your knowledge. Greetings from Brazil.

    • @NStripleseven
      @NStripleseven 4 роки тому

      Weird-looking apostrophe, but I completely agree.

  • @draveeeen5475
    @draveeeen5475 2 роки тому

    what is gameObject reffering to? i assume to the object that has this script as a component, aka the player in this case.

  • @flamingpenny
    @flamingpenny 2 роки тому

    If you do this, and your collider is on a subobject, the OnCollisionEnter2D() will get the gameobject from the parent. The OnTriggerEnter2D() will get the gameobject that the collider is attached too.
    To fix this do OnTriggerEnter2D() => ProcessCollision(collision.gameObject) and OnCollisionEnter2D() => ProcessCollision(collision.collider.gameObject)

  • @RaidenHeaven
    @RaidenHeaven 4 роки тому

    Tips for Beginners : On Collusion/Trigger run by Rigidbody of the GameOjbect, after the FixedUpdate. It returns the Collider that's contact with
    Gravity is always added AFTER the FixedUpdate.
    Physic.Overlap and Ray / Shape cast can used to detect triggers and colliders and you can used them both in Update or FixedUpdate

  • @albertozapata2607
    @albertozapata2607 4 роки тому

    You are a great tutor! Thanks so much for the amazing info!

  • @AetherXIV
    @AetherXIV 3 роки тому

    I'll use this. thanks man

  • @dcry1003
    @dcry1003 3 роки тому

    how come your player isnt falling through the floor after triggerign the red spikes? *in my project whenever i enter my portal collider (which transfers me to the next scene) no matter how i set the portal trigger i always fall of the ground if i didnt add an extra invisible box collider2D in my ground object with its own box collider2D*
    *btw my portal trigger object is more bigger than my player object if that helps*

  • @kalibeastok
    @kalibeastok 4 роки тому

    Great video! Thanks for sharing. I'd like to know how should I handle the inverse context: player hitting enemy?

  • @josekarnikowski1711
    @josekarnikowski1711 2 роки тому

    Really nice video.

  • @marcomarmolejostech
    @marcomarmolejostech 3 роки тому

    Maybe you haven't found it on another collision tutorial because what you are doing is related to a software design principle called DRY (Don't Repeat Yourself) combined with the refactoring method called "Extract Method".

  • @pliniomourao
    @pliniomourao 3 роки тому +2

    This kind of enters in the "Single-responsibility principle" pattern.

  • @lynai8273
    @lynai8273 3 роки тому

    Do you have any idea to set a cooldown for collision damage? my player dies toooo fast when he collides with an enemy after collision checks

  • @art1cuno925
    @art1cuno925 3 роки тому +1

    thx for help

  • @rotub
    @rotub 3 роки тому

    Nice tip - thank you

  • @yogissjkaio
    @yogissjkaio 4 роки тому +1

    Awesome content, thanks for all the amazing info :)

  • @karkeeravindran3649
    @karkeeravindran3649 3 роки тому

    Hello...
    Pl help as soon as possible.
    Tried a 2D game,
    Find the difference game.
    Touching d screen on d object it triggered and result correct, and if touched background image it triggers and results wrong.
    Placed d pointer down.
    If we touched the object, since the pointer moving towards we touched, it automatically triggers the bg first and then the object.
    Results - first msg as wrong, immediately correct.
    How to overcome this. Since bg image is 2dboxcollider even if we increase z axis, it collides .
    Can we directly switch(jump) to the touched point without passing through the bg image area.

    • @pliniomourao
      @pliniomourao 3 роки тому

      In 2D you are not working in 3D space. if an object if Z=1000000... it will collide/trigger other objects at Z=0. So you need to create a management script to tell when an object is collidable or not. Or you can mess with the "Layer Collision Matrix" in the "Project Settings > Physics 2D" to tell the engine which layers can collide with each other.

  • @ibrahimsharckas8929
    @ibrahimsharckas8929 4 роки тому +1

    Another great video thanks alot
    I learned a new thing today

    • @pliniomourao
      @pliniomourao 3 роки тому +1

      I suggest taking a look at the pattern "Single-responsibility principle". It will make your code clean as sometimes we (i assume, because i find references in my code afterwards in refactory) create same actions/functions/behaviour that can be centralized in one place.
      It decreases the maintenance and you have to fix in only one place.

    • @ibrahimsharckas8929
      @ibrahimsharckas8929 3 роки тому

      @@pliniomourao i will thanks

  • @affliction1599
    @affliction1599 3 роки тому

    Hello I’m working on a 2D platformer I ah e a box collider on a moving sprite that’s lava but I want to register more than one collision how do I do this please PM me thanks

  • @mrjeanjean6794
    @mrjeanjean6794 4 роки тому +2

    Thanks! Pretty interesting. I was wondering about moving the collider logic into colliders themselves. I mean: let the spikes applying damages on the target they collide with. The player/hero controller would have a ApplyDamage public method and on collision the spikes would be able to call this ApplyDamage method. With that architecture you solve your initial problem, you can apply damage on every target who has ApplyDamage method and you can give an amount of the damage for each spikes type (like big spike hurts more than smaller ones). Is that a good way to go, you think?

    • @aaronedvalson104
      @aaronedvalson104 4 роки тому +1

      This is how I do it, but I'm a beginner and have been doing it this way because it makes sense to me. If it's a bad practice, hopefully someone comes along to school us. Lol
      But I can see exactly where the idea presented in this video would help out a ton, alongside the way you're talking about.

    • @mrjeanjean6794
      @mrjeanjean6794 4 роки тому +1

      @@aaronedvalson104 Thanks for your comment. I guess the purpose of this video is more about handling multiple colliders types than the damage system itself. It's just an example. In a real world, the right way depends on your needs. IMO, using our logic is more flexible. Dealing with lot of different ennemies and multiple way of being hurt can become a huge mess if you treat it in the main character. I did a bit a research and for example the Corgi Engine works like we do. Once more, it's just my opinion, and it can be achieve in tons of different ways. :)

  • @wheresmyskin
    @wheresmyskin 3 роки тому

    Not really "a better way to manage collisions" but like basics of code structuring and programming. "no code duplication" is like one of the most basic rules to programming.
    "Yeah, few different things do the same action, let's wrap this action into a function and let each thing call the function" :D

  • @xDTHECHEMISTx
    @xDTHECHEMISTx 3 роки тому

    Do you have a video for this where it shows your health bar going down when you get damage? I got your tutorial here to work for me to see the get hit debug code but now im trying to incorporate this code with my health bar code that i currently have set to go down every time i hit my F key. i want that to be for when the enemy collides with my character but i keep getting a weird error

  • @halivudestevez2
    @halivudestevez2 3 роки тому +1

    The difference between trigger and no-trigger : thank you for the tip - while it is so obvious, I missed the point so far...

    • @Zaszz1
      @Zaszz1 3 роки тому

      You might have a spike wall, that you want the player to not be able to pass through, and touching it damages them. You might also have a wall of fire, that you DO want the player to be able to pass through, and touching it damages them. You could achieve this by having a collider on both the fire and the spikes, but have the collider on the fire be trigger, and the collider on the spikes NOT be a trigger.
      The trigger means it stills fires off a collision event, but does not actually stop movement.

  • @dukemagus
    @dukemagus 4 роки тому

    is it more performant to keep this kinds of scripts on Update or make a coroutine with many checks per second (15 or 20 checks every second). the ammount of checks reduces, but i don't know if coroutines add much of an overhead

    • @SNOZ562
      @SNOZ562 4 роки тому

      Coroutines add overhead and the more coroutines you have the worst each one performs. Its also important keep note that coroutines run synchronously with the main thread. This can cause unitended behavior in some ways if you arent careful.
      But to answer your question: no these checks should not be done in an update or corutine. The rrason being is your taking the collision mono api, which is an event driven system and coupling it to your framerate and an update. If anything that would increase the number of calls you are making, not decreasing it. If you see the term "On" infront of a mono api "OnCollisionTrigger", its clueing you in that its an event and that it should be treated as such.

  • @moonneko4035
    @moonneko4035 3 роки тому

    If OnTriggerEnter and OnCollisionEnter have the same function, as showed in this video, why do you have to write both of them in 1 c# script?
    Can you tell me the difference between them?

  • @BikramKha1sa
    @BikramKha1sa 3 роки тому

    thank you brother ...

  • @MaxIzrin
    @MaxIzrin Рік тому

    The reason you don't see such code used much is because you have a very specific use-case where collision and trigger do the same thing.
    It's neat code, but not scalable. *Do not do this.*
    What if a platform (trigger area) heals the player or gives some temporary buff/debuff?
    You need to add that logic into player as well... that can get very messy very quickly.
    That's why I usually see people place the logic in the object initiating the action, and not the entity being affected by it.
    Spikes will damage entities that collide with them, instead of entities having to handle damage when touching spikes.
    And instead of using tags, use interfaces to detect something that can be damaged, i.e: collision.GetComponent() or something like that.

  • @laserbean00001
    @laserbean00001 Рік тому

    I don't understand why you would need to write them twice. Most objects are either trigger or not trigger. Not trigger colliders will never call the OnCollisionEnter function. I guess it could be useful for an arcade type game where you don't necessarily want to put scripts on every spike object.

  • @peacesafe3087
    @peacesafe3087 4 роки тому

    Unity *** Hello. I want to make simple sport game and i want to know how to pick the ball like football or basketball and carrying ball for dribbling or passing or else . I hope u can help me how to do it. Tnx

  • @Blessy4543213
    @Blessy4543213 4 роки тому

    thx

  • @gravious
    @gravious 4 роки тому

    great vid, nice little organisation tip :)
    You've got some mic booming going on, i think your mic arm is tapping the monitor or wall or something, nothing major though

  • @theHaPK
    @theHaPK 3 роки тому

    Amazing! Does this technique work for colliders only or I can use it in other parts of the code?

  • @nomadcrossfire
    @nomadcrossfire 4 роки тому

    I used a similar solution on my last project, I had my logic inside of the CollisionEnter method, and had a call to CollisionEnter inside of TriggerEnter. So essentially triggers and non-triggers all got processed the same

  • @aminullah5939
    @aminullah5939 2 роки тому

    sir you r awsome

  • @programinghub8497
    @programinghub8497 4 роки тому

    I request you to make a video about game world creations (technical stuff) as you have in blood and Mead
    Pls make one i really want it!!

  • @adrianoalmeida7646
    @adrianoalmeida7646 4 роки тому

    Man i love you videos

  • @Pizzaguy2
    @Pizzaguy2 4 роки тому

    sadly it won't detect collision within the same frame

    • @LostRelicGames
      @LostRelicGames  4 роки тому +1

      Good spotting! I made the correction in the sample code with a coroutine

    • @pliniomourao
      @pliniomourao 3 роки тому

      docs.unity3d.com/Manual/ExecutionOrder.html
      This might be of use for you to address this details.

  • @ApoLk_
    @ApoLk_ Рік тому

    im so shit at codig i cant make this work, the chacater collides and nothing happens why the heck did i chose to study this im screwed

    • @ApoLk_
      @ApoLk_ Рік тому

      nevermind i fixed it i love programming

    • @LostRelicGames
      @LostRelicGames  Рік тому +1

      Haha, sounds like me every day. The solution or a new problem is always moments away. Enjoy the adventure , it gets easier!

  • @ethanloewald3340
    @ethanloewald3340 4 роки тому

    Great tutorial! One question though. What happens when you need to access the data from the collision data. Would a gameObject.GetComponent call suffice?

    • @SNOZ562
      @SNOZ562 4 роки тому +1

      Getcomponent should only be called on startup imo to cache references. Getcomponent is expensive and youvshould never be fetching components at runtime as that call cost adds up over time. This is why you should cache your transform components when dealing with movement, cause accessing them via gameobject.transform has a hidden getcomponent call

    • @LostRelicGames
      @LostRelicGames  4 роки тому +3

      @@SNOZ562 To suggest GetComponent should *never* be called outside of start up functions is completely unrealistic. Outside of the Update loop, the performance implications are negligible at best. We are trying to ship indie games here, not build Hadron colliders.

  • @OpenYoureyes304
    @OpenYoureyes304 3 роки тому

    so john wick is a game dev now huh?

  • @kennisdev
    @kennisdev 4 роки тому +1

    Parabens pelo video, n sei ingles mas pude entender um minimo, e quero pedir, se possivel, q vc faça um video sobre melhores formas de fazer o movimento do player para mobile eu uso ums truques mas parecem muito errados
    Thanks

  • @darkotomic943
    @darkotomic943 3 роки тому

    Even better, use Actions/Events

  • @FM_GOBi
    @FM_GOBi 4 роки тому +1

    If you duplicate a piece of code once, encapsulate it.
    If you duplicate a piece of code twice, give up on programming.

  • @animationsbelike
    @animationsbelike 2 роки тому

    ÓMG thank you! :DDDD

  • @nGAGE0nline
    @nGAGE0nline 4 роки тому

    Or you could just have it return a bool, as you might have different behavior for Trigger and collider. Let's say: collider only damages when you fall onto it, but shouldnt damage when you walk up against it, whereas the trigger version could be some lava on the ground and it should continuously tick some damage while you stand on it.
    I honestly expected you to go a little further with this video and am a bit disappointed to see essentially a basics tutorial of "Hey, you can call other methods too" video.

  • @johnx140
    @johnx140 3 роки тому +1

    Isnt this just... making a function?

  • @jamesc2683
    @jamesc2683 4 роки тому

    This makes me want to go back and recode old projects...

  • @DesnesCitrus
    @DesnesCitrus 4 роки тому +1

    I really love your Videos! They are way more helpfull than others! I would like to know what do you think about my newest Video with you in it. Keep up the good content!

  • @CzechHustler
    @CzechHustler 2 роки тому

    Ty jsi Čech že? :D

  • @pndaedits2364
    @pndaedits2364 2 роки тому

  • @vast634
    @vast634 3 роки тому

    Thats one loud keyboard

  • @بساطةالبرمجةبيونتي

    thank you it is arbic

  • @ShadowBanned0
    @ShadowBanned0 4 роки тому

    res

  • @Gers217
    @Gers217 4 роки тому

    This isn't so great if you need info about the collision

  • @ManjeetKumar-xk8jf
    @ManjeetKumar-xk8jf 3 роки тому +1

    I don't know man but you look like Jesus.

    • @Flashxy78
      @Flashxy78 7 місяців тому

      🤣🤣🤣🤣🤣

  • @francoismentec4260
    @francoismentec4260 2 роки тому

    Wow, making a function for code that occurs in multiple places... Who would have thought of that...
    Seriously when you put beginner and unity in the same title I think that as a unity beginner I am going to learn something.
    Stop making Unity tutorial that are actually coding tutorial, I am watching Unity tutorial to learn about the game engine not basic programming stuff. There is nothing wrong about making coding tutorial, but phrasing it as if you were going to teach us anything about collisions in Unity is wrong.