Identify both objects that is colliding from one scrip

I have two similar game objects on my scene that act as player protection areas, meaning that objects that is within these areas is protected.

The two areas have rigidbody2d and collider2d attached and the player objects have collider2d attached.

I have a script attached to the areas with “Void OnTriggerStay2D(Collider2D col) {”.

This is triggered when i move a player object into the player protection areas and i am also able to identify these objects using the “col.tag” parameter.

However, is it possible to also identify the player protection area GameObjects in the same script?

Do you mean getting the gameObject of the area you are colliding with? (if the script is on the player)

If so, the variable gameObject is an inherited member of Collider2D and you can call col.gameObject. Most if not all components can do that.

But your wording is that the script is on the areas themselves. If that’s the case you already know the objects, no? If you want to get all the area objects you could tag them and use Unity - Scripting API: GameObject.FindGameObjectsWithTag I use tags in my personal projects but in a big collaborative project like at work we don’t use tags. We find the objects that have the script like this: way to get all object with a certain component/script attached - Questions & Answers - Unity Discussions

I’m a little confused by the question but hopefully this info helps

The object you’re looking for will be the object that the OnTriggerStay is executing against - so you can reference it simply as “gameObject” in code. The other object (in this case the Player) is the collider that you’ve called “col” (col.gameObject for it’s GameObject).

private void OnTriggerStay(Collider col)
{
    Debug.Log(string.Format("{0} - I'm the player area that has been collided with.", gameObject.name));
    Debug.Log(string.Format("{0} - I'm the object that has entered the area.", col.gameObject.name));
}

EDIT: Just for completeness, you might not want to use OnTriggerStay in your case. I would think that OnTriggerEnter you’d set a player flag like IsProtected = true, and then OnTriggerExit, IsProtected = false.

Thanks, should have understand this from start :slight_smile:

No - as far as questions go, that’s a decent one. When I started using Unity, I asked some genuinely dumb questions :slight_smile:

:slight_smile: