- Home /
How to detect multiple Colliders in the same object?
Hello, I am making a 2D game, where the players has 2 Colliders, (a Circle and a Box Collider 2D) And at some point I use, to transform the player colliders into triggers:
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.tag == "Player") {
other.gameObject.collider2D.isTrigger = true;
}
But this way it only acesses the first collider in the players inspector and not both...
Can anyone tell me how to detect both colliders?
Answer by spiceboy9994 · Jan 19, 2015 at 06:40 PM
Additional to Simon Larsen's answers you may want to access specific properties from each collider type so, it could be:
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.tag == "Player") {
foreach (Collider2D collider in other.gameObject.GetComponents<Collider2D>())
{
collider.isTrigger = true;
if (collider is BoxCollider2D) {
BoxCollider2D myBoxCollider = (BoxCollider2D)collider;
//Do some stuff with the box collider
}
else if (collider is CircleCollider2D) {
CircleCollider2D myCircleCollider = (CircleCollider2D)collider;
//Do some stuff with the cyrcle collider
}
}
}
}
Hope this helps
Answer by Simon-Larsen · Jan 19, 2015 at 06:11 PM
You could fetch all the components of a certain type and iterate through the components by doing the following.
void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.tag == "Player") {
foreach (Collider2D collider in other.gameObject.GetComponents<Collider2D>())
{
collider.isTrigger = true;
}
}
}
In case some of your colliders are placed as children on the collider you could also search through the children http://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html
thank you very much ! I always forgot about those usefull foreach loops :/
Your answer
Follow this Question
Related Questions
2D Coins and Points 1 Answer
Colliders 2d apparently touch each other even if they should not. 2 Answers
Do I really have to do this? 2 Answers
Strange Collisions in 2D 1 Answer
Player with RigidBody2D "bouncing" on EdgeCollider 0 Answers