Haytam95
Haytam95

Reputation: 307

Check which collider trigger in Unity3D

Context

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

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")

    }

Upvotes: 3

Views: 4198

Answers (2)

MSB
MSB

Reputation: 884

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)

Upvotes: 4

user601
user601

Reputation: 114

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

Check unity documentation about collider here for more info.

Upvotes: 1

Related Questions