- Home /
Getting multiple Polygon Collider 2D on script
Hello guys, I have a character in my game and I have different PolygonCollider2D attached to them, in order to enable/disable them depending on which sprite animation is playing at the moment. That is because the idle animation is different than the running or jumping one, so as I can't edit the vertices of the PollygonCollider, I just attached 3 of them with all of them having different shapes of course.
The thing is i don't know how to identify these components in order to get them by script and enabling or desabling them. I can make:
PolygonCollider2D collider1 = gameObject.GetComponent<PolygonCollider2D> ();
But I don't know which one would be cause there's nothing there to identify them.
Thanks in advance.
Answer by largow · Apr 14, 2014 at 12:47 PM
Your answer was useful. Thanks!
I also found another way, by doing this thing:
public PolygonCollider2D[] lstPolCols;
void Start(){
lstPolCols = gameObject.GetComponents<PolygonCollider2D> (); //use GetComponents
//And now i enable or disable them just when i want to: Example:
if(character.IsRunning())
lst.PolsCols[1].enabled = true;
//cause the 'running' polygon collider is the second one i attached,
// so it will be at the second position [1].
}
}
I am working on game where i have three different sprites for hero guy. Up,middle and down.
I did multiple colliders as here suggested. I can assign colliders easily and change them to correspond sprite i am showing.
However if i drag sprites to different PolygonCollider2D's it automatically updates rest of colliders to same shape. So if i drag down position sprite to any PolygonCollider2D's also the rest of the colliders have same shape.
Am i missing something here?
Answer by Patel-Sagar · Apr 14, 2014 at 05:47 AM
You can get reference of each of them in start. you can define it public as below.
public PolygonCollider2D p1, p2, p3;
then you can add reference to it in inspector itself by drag and drop.
if you are creating these colliders in start by addComponent, then you can give reference there also as below.and then use this variable to access in whole script.
p1 = gameObject.AddComponent(); print(p1.points.Length);