Detect collision from different objects?
I couldn't come up with a suitable title for this question but I'll explain.
I have a collision box, which holds a script. This script has an if statement that detects collision from object "Cube001" and sends a Debug.Log to console.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cubeDetect : MonoBehaviour {
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.name == "Cube001")
{
Debug.Log("Cube001 hit!");
}
}
}
With this method, the box collider knows what cube has touched it, as I have instructed so with
collision.gameObject.name == "Cube001"
But say if I have 10 cubes colliding with the collision box, how can I change the if statement so instead of writing another 9 if statements that check if it touches the collision box, I can just have 1 if statement that just first detects a collision from another cube, knows what cube hit the box, and with this knowledge, is able to do a Debug.Log to display the name of the cube that hit the box.
I've tried going through the documentation for OnCollisionEnter but couldn't find anything to help with this.
Answer by Hellium · Feb 09, 2018 at 03:00 PM
Using layers
Create a new layer called "Cubes"
Assign the cubes (Cube001 → Cube010) this new layer
Create a 2nd layer called "CubesDetector"
Change the collision detection matrix so that the
Cubes
layer only detect collisions withCubesDetector
In your OnCollisionEnter function, you know that the object referenced by
collision.gameObject
is a cube, and nothing else
Using tags
Create a new tag called "Cube"
Check the tag of the object in
OnCollisionEnter
if (collision.gameObject.CompareTag("Cube") ) { Debug.Log(collision.gameObject.name + " hit!"); }
Using regular expression
if (System.Text.RegularExpressions.Regex.IsMatch(collision.gameObject.name, "^Cube\\d{3}$") )
{
Debug.Log(collision.gameObject.name + " hit!");
}
This is great, I actually managed to do this the same way! Is there much of a difference between using collision.collider.CompareTag as opposed to collision.collider.tag?
Your answer
![](https://koobas.hobune.stream/wayback/20220612152306im_/https://answers.unity.com/themes/thub/images/avi.jpg)