Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check which collider trigger in Unity3D

Context

I'm developing an AbstractAliveEntity, which have basically three functions:

  • Sight: Detect interactable objects. (Collider + Raycast)
  • Detection: Detect anothers AbstractAliveEntities (Collider + Raycast)
  • Hearing: Hear noises (Collider)

Currently i'm creating via script empty gameObjects with these colliders.

What i want

I want to know which collider was trigger in OnTriggerEnter and OnTriggerExit

Code

Creating the Sphere collider

private void Start() {

        // Creating empty gameObject
        sightGameObject = new GameObject("Sight");
        sightGameObject.transform.parent = transform;
        sightGameObject.transform.localPosition = new Vector3(0, 0, 0);

        // Add Component Sphere
        _sightInteractable = sightGameObject.AddComponent<SphereCollider>();

//        _sightInteractable = gameObject.AddComponent<SphereCollider>();
        _sightInteractable.radius = radiusInteractableDetection;
        _sightInteractable.isTrigger = true;
}

Detecting

private void OnTriggerEnter(Collider other) {

        // How can i detect which collider was?? this.gameObject = "Player" (i want "Sight")

    }
like image 494
Haytam95 Avatar asked Feb 27 '26 16:02

Haytam95


2 Answers

Since Unity is originally designed around a component based approach my approach would be to split up the three separate "detection" systems into separate GameObjects with their own collider and script.

  • AliveEntity
    • SightController
      • ColliderA
    • DetectionController
      • ColliderB
    • HearingController
      • ColliderC

Then you can use the OnTrigger in each separate script to fire a notification to the main AbstractAliveEntity which then handles them on a case by case basis.

Main Script

OnSight(Collider other) {
  // Do sight related actions here
}

OnDetection(Collider other) {
  // Do detetction related actions here
}

OnHearing(Collider other) {
  // Do hearing related actions here
}

Then for each respetive detector:

// reference to master script
public AbstractAliveEntity aae;

OnTriggerEnter(Collider other) {
  // replace function with whatever you want to use
  aae.OnSight(other)
}

The Added advantage here is that you are now also free to design 'blind' or 'deaf' Entities without all too much hassle. (You simply do not add the respective components)

like image 133
MSB Avatar answered Mar 02 '26 06:03

MSB


other.gameObject to get the gameObject the other collider is attached to.

Check unity documentation about collider here for more info.

like image 20
user601 Avatar answered Mar 02 '26 06:03

user601



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!