Hi! I have a Game Object which has 4 polygon colliders 2D that change depending on which frame of the animation is played by the sprite… now I want to disable them but I can’t find the way to do that… any help would be really appreciated @Hellium
Thanks! Here is part of the script that Im using
[SerializeField]
public PolygonCollider2D[] colliders;
private int currentColliderIndex = 0;
void Die()
{
animator.SetBool("IsDead", true);
foreach(PolygonCollider2D other in GetComponent<PolygonCollider2D>())
{
other.enabled = false;
}
this.enabled = false;
}
public void SetColliderForSprite( int spriteNum )
{
colliders[currentColliderIndex].enabled = false;
currentColliderIndex = spriteNum;
colliders[currentColliderIndex].enabled = true;
}
}
Instead of going for ‘GetComponent’ and ‘PolygonCollider2D’ your best bet is to switch to ‘GetComponents’ and ‘Collider2D’ instead.
GetComponents< Type>(): returns all the components of type on the same gameobject
Collider2D: instead of specifying which collider you want you can use Collider2D instead, this gets all the colliders on the gameobject. (If this isn’t what you want, return to using ‘PolygonCollider2D’
Hope this helps!
[SerializeField]
public PolygonCollider2D[] colliders;
private int currentColliderIndex = 0;
void Die()
{
animator.SetBool("IsDead", true);
foreach(Collider2D col in GetComponents<Collider2D>())
{
col.enabled = false;
}
this.enabled = false;
}
public void SetColliderForSprite(int spriteNum)
{
colliders[currentColliderIndex].enabled = false;
currentColliderIndex = spriteNum;
colliders[currentColliderIndex].enabled = true;
}
I don’t think your question is very clear, but I’ll share what I know. You can just tell me if it is what you’re after.
If I were in your shoes, I would just enable/disable the colliders inside the animation.
Though if you want to use your method, the scripts you’ve shared should do it. You just need to make sure you drag the right ones in the inspector. If you’re looking for the mistake in your “Die()” function, it has a syntax error, you can use either one of these instead.
void Die()
{
animator.SetBool("IsDead", true);
foreach(PolygonCollider2D other in GetComponents<PolygonCollider2D>())
{
other.enabled = false;
}
this.enabled = false;
}
void Die()
{
animator.SetBool("IsDead", true);
foreach(PolygonCollider2D other in colliders)
{
other.enabled = false;
}
this.enabled = false;
}
for(int i = 0; i < 5; i++){
colliders*.enabled = false;*
}
This code runs through your array of polygon colliders and disables them.
Edit:
Sorry did you want to disable a certain collider or all at once
Use GetComponentsInChildren on the parent object to get all colliders. And myaarpmedicare for those colliders who ‘isTrigger’ is true, set enabled false.
foreach(var c in gameObjectParentName. GetComponentsInChildren<Collider>())
{
if(c. isTrigger) c. enabled = false;
}