In this Unity tutorial, we'll be discussing how to create and use colliders in Unity. We'll cover topics like how to create colliders, OnCollision and OnTrigger events, how to set collision filtering preferences, and more!
If you're new to Unity or want to learn more about collision filtering, then this tutorial is for you! We'll cover everything you need to know to create and use colliders in Unity for efficient game development. Let us help you master Unity's Colliders!
****************************
LINKS MENTIONED IN THIS VIDEO:
Rigidbodies (Learn more about Collision Detection) 👇
https://youtu.be/Y3xkgpCukow
Collectibles (Collision filtering + Inheritance) 👇
https://youtu.be/Vo3RDWiupCg
Collision Detection Algorithms 👇
https://docs.unity3d.com/Manual/ContinuousCollisionDetection.html
Modular Castle Asset Pack 👇
https://assetstore.unity.com/packages/3d/environments/dungeons/modular-castle-121360
Read more about Colliders 👇
https://docs.unity3d.com/ScriptReference/Collider.html
****************************
For doubts and stuff, join our discord club👇
https://discord.gg/kVjSMDHMda
Check out my Instagram 👇
https://www.instagram.com/anandev.0/
*****************************
TIMESTAMPS🔍
0:00 Colliders in Unity
1:07 How to add colliders
1:28 Compound Colliders
3:03 Physics Materials
3:27 Static and Dynamic Colliders
3:54 Collision Detection
4:07 OnCollision Events
6:20 Triggers
6:57 OnTrigger Events
7:50 Trigger Detection with compound collider (Example)
9:07 Filtering Collisions
9:20 Using Tags
9:53 Using Layers
10:35 Tags vs Layers
11:19 Using GetComponent() function
11:48 Using Collision Matrix
12:35 IgnoreCollision()
13:36 Which Collision Filtering to Use?
13:58 Class Inheritance and Collisions?
14:34 Outrooooooo
#unitytutorials #gamedevelopment #unity3d #unitytutorial #collision
If you have any questions, comment below, and I will try to answer them to the best of my knowledge.
Thank you for watching the video and reading this description. Take care.
Colliders are a fundamental aspect of creating
interactions in your games, and understanding how they work is essential. So, let's get started with Colliders! Let's talk about what colliders are and why
they are important in Unity. In simple terms, colliders are components
in Unity that define the boundaries of our game objects and help us detect collisions
and trigger events. There are different types of Colliders available in Unity. Essentially, they can be classified into 2D
and 3D Colliders.
Box Collider, Sphere Collider, and Capsule
Collider, and their 2D counterparts, are basic shapes that can represent a wide
range of objects in our game. Therefore, they are commonly used. It is recommended to pick a collider for a
GameObject that best resembles the shape of the object. Unity also has more complex colliders like
Mesh Collider, which allows you to use custom mesh shapes for collisions, and Terrain Collider,
which is specifically designed for terrains. There also exists a Polygon
Collider, which
is pretty useful for 2D games. It can be edited to form any shape within
the editor itself, You can add colliders via the Inspector, and you can change the properties of the collider, such as the size and shape. This part is fairly straightforward. Again, I HIGHLY recommend choosing a simple
shape for a collider that best resembles the object. This makes calculations easy for the computer, unlike the Mesh Collider, which can be difficult based on the complexity of the mesh. Now l
et's talk about Compound colliders. Compound Colliders in Unity allow you to create
complex collision shapes by combining multiple simpler colliders into a single compound collider. Instead of using a single collider shape that
matches the entire object's geometry, you can use multiple colliders to approximate
the shape more accurately and efficiently. To create a compound collider in Unity, you
typically create child GameObjects and attach separate colliders to each child. Then, you add a Rigid
body component to the
parent GameObject to enable physics simulation if necessary. The child colliders are automatically combined
into a compound collider under the parent GameObject. Just a thing to note, while using compound
colliders is that although it makes the complex stuff easy for us, it also makes the simple
ones a bit harder. Allow me to elaborate. The physics and collision detection part is
going to be accurate. But let's say you want to do the simple stuff. A trigger detection, using
the OnTrigger events. We'll discuss more about that in-depth later
in the video. But with a compound collider, Unity, for some
reason, decided to make sure that each collider would be able
to trigger the event separately, and therefore it may be called
multiple times in a single frame. Don't worry! We would only need to perform a bunch of calculations and spend 24 hours on it just to open a stupid door. We will also look at how to work with compound
colliders later in the video. But the main
point being, if you could get
away without using compound colliders, do it. It will save you a lot of headache. Only go for it if you want realistic physics
calculations to be made. You can also create Physics Materials to add
more spice. A Physics Material is an asset that you can
create, and you can use it to adjust how the collider
behaves during a physical interaction. By adjusting properties like friction and bounciness, you can control how objects slide,
interact, and bounce off each oth
er. For physics materials to work, you need a
Rigidbody component attached to the body. I also want to introduce the terminology of
Static and Dynamic colliders. Static colliders are colliders without a Rigidbody
component, while the dynamic ones
do contain a Rigidbody component. Static colliders mean that they will not
move, no matter what happens, like floors, walls, and buildings. Dynamic colliders will respond to collision based on the properties of the Rigidbody component, and of course,
the Physics Material. Now, let's talk about collision detection
and collision events. Collision detection is the process of detecting
when two colliders intersect in the game world. Unity provides built-in collision detection
algorithms that work in real-time. When a collision happens, Unity throws a bash
of collision events! We're talking about OnCollisionEnter() , OnCollisionStay(),
and OnCollisionExit()! They let you know when a collision starts,
hangs around, or decides to peace out. Enter,
Stay, and Exit. And the best part? You can tap into these events
to create gameplay logic. OnCollision events have a parameter of type
Collision. This parameter can be used to get information
about the collision, such as the point of impact
and, of course, the collider object. This is really cool. You don't really have to study the syntax; you can simply write "OnCo" in your script, and Visual Studio gives you prompts to choose
the required function, and it auto-completes it on its own. For On
CollisionEnter() to be called, the colliders must physically collide
with each other for the first frame, during the current frame. You can use it to detect when the player collides
with an obstacle and apply damage, play sound effects, trigger animations, etc. If the collision continues and the colliders
keep touching in subsequent frames without separating, the OnCollisionStay() event
will keep on firing. This can be used for continuous interactions,
like making a platform move, only when th
e player touches it. When the colliders cease to collide
and part ways, the OnCollisionExit() event jumps in, bidding farewell to the collision journey. An Important thing to mention is that for
the OnCollision events to be called, at least one of the colliders
involved in the collision must have a Rigidbody or a Rigidbody2D
component attached. In other words, at least one of the colliders
must be dynamic. It's also important to note that the OnCollision
events are called on the GameObject that
has the script with the OnCollision function,
not on the colliders themselves. If you want to learn more about collision
detection, I recommend checking out THIS video on Rigidbodies in Unity because collision detection actually has
nothing to do with the colliders themselves; they are controlled by the Physics Engine. So I highly recommend checking it out. Now, we need a way to filter collision detection
based on specific conditions. For example, we may want to check if it is
specifically the
player that is colliding with this object. We will discuss this in just a little bit,
but first, let's talk about triggers. Triggers are colliders that are designed to
detect collisions without causing any physical commotion. Let's say you need to set up an event when
your character enters a specific area or you want to detect when the player grabs a power-up or interacts with an object. Triggers are probably the easiest solution
to those problems! To turn a collider into a trigger, simply check
the "Is Trigger" box,
and voila! Now, they won't physically collide or get
in the way of the other colliders. They're all about detection and making things happen
without any physical fuss. Unity has three trigger events: OnTriggerEnter(),
OnTriggerStay(), and OnTriggerExit(). OnTriggerEnter() is called when a collider
enters the trigger zone, OnTriggerStay() is called each frame a collider
stays in the trigger zone, and OnTriggerExit() is called when a collider
exits the trigger zone. You
can use these events to implement specific
actions or behaviors, such as opening a door, or triggering a cutscene. Unlike OnCollision events, OnTrigger events
do not have a parameter of type Collision. Instead, they have a parameter of type Collider. Because one of the colliders is a trigger,
there is no physical collision happening. In most cases, you need to reference the
components of the Collider that hit the trigger and that's why the signatures are different. Also, The conditions for OnT
rigger Events to be
called, are the same as the ones of the OnCollision events. In this simple scene, I have a player character
and a trigger zone around a door. You can see that this character
has a compound collider. I have attached a trigger collider to the door, and I have implemented the OnTriggerEnter() event in my script. If you are only using a simple collider, then a simple OnTriggerEnter() and OnTriggerExit()
event should be enough. But because we are using a compound collider,
thing
s are a little bit different. Because compound colliders register OnCollision and OnTrigger events
for each individual collider separately, we would need to use a boolean
in this case. Similarly, I can implement the
OnTriggerExit() event to close the door or perform other actions when
the player exits the trigger zone. Just to make sure all of the colliders leave
the trigger zone, I used an integer and incremented it on each OnTriggerEnter, and decremented it on exit, and only closed the door
when it becomes zero. This setup needs more tweaking,
perhaps a timer, because I made a compound collider, there exist lots of bugs just to
make a STUPID door open and close, especially when you animate the player. It causes colliders to go back in and out, causing all sorts of headaches. Which brings me to what I said earlier in
the video, use compound colliders, only when you need to! You can see in this script that I compared
the tag of the colliding object to "Player" to ensure that it is
indeed the player that
entered the zone. There are different ways to filter collisions, and let's discuss some effective methods one by one. Using Tags. You can utilize the GameObject.CompareTag() function to filter different types of GameObjects. This approach is much faster compared to using
the Equality operator because, this function takes advantage of the fact that Unity stores tag values
in a separate data structure and therefore, it is indeed fast. While the other technique
involves str
ing operations. And I know that
sounds too complicated. Essentially, using the CompareTag() function
is faster in my opinion. Using Layers. You can also filter objects using layers. In Unity, layers are internally
stored as integers, so they are generally faster than tags. You can check for a layer using the following
steps: You need to first, create a layerIndex and use LayerMask.NameToLayer() function to get that integer value of the required layer. Then inside the event, you check
if they ar
e the same, like this. If you want to check for
collisions with multiple layers, you can use a LayerMask instead. In this case, you can choose which layers
to filter in the Inspector and then utilize bit masking
and bit shifting operations to check for collisions. These operations are binary operations and
are known for their speed and efficiency. Now, When should you choose tags over layers? In my opinion, You should use tags when
you prefer a straightforward approach. If you find tags easie
r to work with,
go ahead and use them. However, if using tags causes
any performance issues, which can occur if you have a large number of
collisions happening simultaneously, you may want to consider using layers
for improved performance. Layers are particularly useful when you need
to handle complex scenarios and interactions. Additionally, if you are using third-party
plugins or other external resources, tags can be more convenient. However, if your project requires a more solid
and effic
ient solution, layers are a reliable choice. You can also use the GetComponent() function
to filter collisions based on components. This method is generally fast if you
successfully retrieve the component. However, if the function returns null,
it can be slower. This performance consideration is that not significant
for games with simple collisions. However, for games with a large number of
collisions, you may need to add a layer on top of this. Pun intended. This will make more sense when we
discuss
the best form of filtering, which is using the Collision Matrix. To access the Collision Matrix, navigate to
Edit > Project Settings > Physics (or Physics2D). Here, you will find the collision matrix
represented as a grid, which includes all layers in your project. In the Layer Collision Matrix, you have the ability to configure which layers
should collide with each other. By default, all layers are set to collide
with one another. However, you can customize the collision behavior
by u
nchecking the checkboxes that correspond to the layers
you want to exclude from collisions. For example, if you want to prevent collisions
between the player and the player's projectiles, you can uncheck the intersection
of the Player row and the Projectiles column. It's important to ensure that all relevant
prefabs are assigned to the appropriate layers. Lastly, an important filtering method to know
is the IgnoreCollision() function. There is a useful function called Physics.IgnoreCollision()
or Physics2D.IgnoreCollision(), that allows that allows you to dynamically enable or disable
collisions between two colliders during runtime. By passing in two colliders
and a boolean value, you can control whether collisions
should occur between them. Setting the boolean to true disables collisions,
while setting it to false allows collisions. It's important to note that this function
is not persistent. That is, if the game is stopped or a collider is disabled, the IgnoreCollision state will
be lost, and you'll need to call the function again. Now, which filtering method should you use? The answer lies in a combination
of these methods. I highly recommend ALWAYS
utilizing the Collision Matrix, as it effectively eliminates unwanted collisions and provides precise control
over collision behavior. If you are certain that a collider is exclusively
assigned to a single layer, you can perform a GetComponent() check
to filter collisions. However, if the collider could belong to multiple
layers, using LayerMask is a more suitable approach. Tags can also be used for additional filtering, especially during prototyping
or when you prefer a simpler implementation. Tags are fast and can be effective
in certain scenarios. To take your filtering to the next level, you can incorporate the concept of Class Inheritance. By implementing inheritance, you can avoid the need for
explicit checks inside collision events, resulting in cleaner code. This approach enhances code organization and
maintainability as well. If you want to learn more about this,
I will link a video right now, which will show you how I implemented
a complete collectibles package, which you can reuse in all your projects, within just 10 minutes. We use the collision matrix over there as well and added the concept of Inheritance to spice things up. The link will also be in the description.
Cool. That's all we have today for colliders. I hope you have found this video useful. If you have any suggestions for
t
he next component to cover, please let me know in the comments below. I'm currently considering
the Animator component. But I would love to hear your thoughts. Take care, and see you next time. BUBYEEE!
Comments
Sorry for the loud sound effects 😭 That's it. Have a beautiful day :)
Criminally underrated unity game dev youtube channel Love the tutorials
This is literally a wealth of experience and knowledge, thank you very much Sir
Here before this channel blows up!!
im using Unity nearly ten years and this is one of the best tutorial ive ever seen
You made one of the best Unity tutorials I've ever seen.😍
Thank you for your video, clear, concise and very educational. Almost always, we think that because they are basic topics they are not so important, but they really are. I just discovered your channel and I find your content very good. Great job!
The best video i stumbled upon .you earned a sub bro,the only request i would have is upload frequently and stick to the topics like this and can you tone down sound effects a bit low .
This deserves more views. So concise! One way you could have gotten around the compound collider for your character is to create an empty object in the hierarchy of your player with a tag of "PlayerPresence" and a trigger capsule collider then check if the door has OnTriggerEnter/Exit with that tag. Your example is good if you want to be more precise, but in the case of the door you probably don't need to be.
you are doing great work .. keep up .. can you make a video about how is unity working in background i mean what is the main class in unity and what is mean by namespace and this stuff thanks
Been having a hard time with my collisions in my prototype,this vid might have been the answer to my issues😂
To not get performace hit if you use the getComponent function and returns null use the tryGetComponent function instead which returns a boolean if the component you are looking for is null or not and outputs it if it isnt without any performance hits if its not
2:45 KILLED ME HAAHAHAHAHAH
Very cool vidéo ! The sound effects are a bit too loud for me :)