How to check the type of GameObject you are colliding with?

How to check the type of GameObject you are colliding with?

void OnTriggerEnter (Collider other) { // If the touching GameObject has a Component called Enemy, delete it. if (other.GetComponent ()) { Destroy (other.gameObject); } } GetComponent () searches a GameObject and retrieves a Component named Enemy. If such a Component is not found, it returns null.

Can you check the name of a GameObject?

If you have specific types of GameObjects that are unique (i.e. only 1 of it exists at any given time), you can give it a unique name and simply check its name instead of its tag. In case you don’t know, there are a couple of ways you can set the name of a GameObject.

How to check for collisions between moving objects?

You are going to check for collisions between the moving objects. That requires you to loop over all objects and check if any of them overlaps with another. You’ll need a nested for loop for this. Take a look at the example: All objects are checked for intersection with each other.

Why is the transform of the bottom GameObject not changing?

Transform.position returns a copy of a Vector3 instead of the reference. So modifying the copy won’t affect the original Vector3 position. Since Bottom is a child of Walls, it is better to use Walls/Button in your Find function as that will tell Unity to look for the Bottom GameObject only under Walls hierarchy.

How to detect collision with a specific object?

After we set a tag for the object, we can detect the specific object by its tag name. We will first check if our game object has the specified tag name and then destroy it on Collision with another Object. Below is our C# code to detect collision with a specific object in Unity: void OnCollisionEnter (Collision targetObj) {

How to detect collision in Unity game engine?

The Unity game engine already provides the collision event API or function which is OnCollisionEnter. We can use it in our C#. Below is the syntax to perform and execute the code after the collision: Inside the OnCollisionEnter function, we can perform our task.

Why is collision detection important in game development?

Our enemies destroy in the game because there is a collision detection between our enemy and bullet. Of course, you may realize that detecting collisions is a quite important part in game development. So, in this tutorial, I am going to show you how to detect collision between two objects so that you can apply it to your game development project.