In this tutorial, we will see how to detect collision in unity 3D between different game objects. We will use Collision class to detect the collisions between game objects.
- Unity Windows
- Unity On Collision Enter 2ds
- Unity On Collision Enter 2d Form
- On Collision Enter 3d
Collision detection in Unity is one of the most confusing aspects of Unity scripting for the aspiring game developer. No matter how many times you try to understand it, there's always a case where your methods aren't called and you have no idea why. The other Rigidbody2D involved in the collision with the rigidbody. RelativeVelocity: The relative linear velocity of the two colliding objects (Read Only). Rigidbody: The incoming Rigidbody2D involved in the collision with the otherRigidbody. Transform: The Transform of the incoming object involved in the collision.
We will use below scene for demo.
We will move player object with keyboard input and check it’s collision with other objects.
Steps to detect collision in Unity 3D
The game object on which collision detection will be triggered should be having Rigid Body and Collider components. For this demo, we will attach Rigid body component to the player game object. Box collider is already available to primitive Cube objects.
Freepbx ivr tutorial. Make sure Is Kinematic check box is unchecked.
Attach Collider components to the other game objects. Here we have added Box Collider to Ground and Enemy Game Objects. Rigid Body component is optional. Make sure that “Is Trigger” checkbox is unchecked.
Step 3: Attach below script to Player game object.
LogCollsiionEnter.text='On Collision Enter: '+collision.collider.name;
LogCollisionStay.text='On Collision stay: '+collision.collider.name;
LogCollisionExit.text='On Collision exit: '+collision.collider.name;
Our setup is complete. Run the application to see the results.
Collide with specific objects – layers
Unity On Collision Enter 2ds
We can also detect collision for specific set of objects. We can use layers for the same. For this example, we will do the following changes:
- Create three different layers, Ground, Player and Enemy. Apply these layers to respective game objects. To know more about layers, checkout this layer masking tutorial.
- Open Physics settings. (Edit -> Project settings -> Physics)
- There is Layer Collision Matrix in physics settings. Here we can check that which layer will interact with other layers.
With above settings Player Layer Objects with not collide with Enemy layered objects.
Hope you get an idea about to detect collision in unity 3D. Post your comments for queries and feedback. Thanks for reading.
Unity On Collision Enter 2d FormThe following two tabs change content below.
On Collision Enter 3d
- Using Transparent Material in Unity 3D - February 8, 2021
- Getting started with UI Toolkit : Unity 3D Tutorial - December 30, 2020
- Using Events in Unity 3D - May 2, 2020