- Home /
Add PolygonCollider2D to sprite at runtime without it trying to caluclate its shape
I'm adding the PolygonCollider2D component to some of my sprites at runtime and set their points via script. I've noticed a warning, telling me that sprite outline creation failed, because the texture was not readable. That's all fine for me, I actually don't want the collider to automatically try to create it's shape. Can I disable this when adding the component or does it always happen? Or can I simply ignore the warning?
I really want to stick to procedural creation, because it wouldn't make sense for me to create so many different prefabs just to have those collider shapes.
Answer by lassade · Aug 19, 2016 at 03:40 AM
My guess it will be just fine. Probably Unity is calling the Reset function implemented in the PolygonCollider2D component to create the default collider, however it's only called in editor. https://docs.unity3d.com/ScriptReference/MonoBehaviour.Reset.html
You can verify this by build a dev build of your game and look at the game logs to see if this warning is there. Even if it is there your game should run no problem whatsoever.
Answer by Alexey_Feskov · Oct 10, 2020 at 02:56 PM
I've found solution works both in runtime and Editor
public static void AddPolygonCollider2D(GameObject go, Sprite sprite)
{
PolygonCollider2D polygon = go.AddComponent<PolygonCollider2D>();
int shapeCount = sprite.GetPhysicsShapeCount();
polygon.pathCount = shapeCount;
var points = new List<Vector2>(64);
for (int i = 0; i < shapeCount; i++)
{
sprite.GetPhysicsShape(i, points);
polygon.SetPath(i, points);
}
}
Usage example:
private void Awake()
{
if (TryGetComponent(out SpriteRenderer rend) && rend.sprite)
{
AddPolygonCollider2D(gameObject, rend.sprite);
}
}
I hope this will help someone who googling "Add PolygonCollider2D to SpriteRenderer at runtime" :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612091114im_/https://answers.unity.com/themes/thub/images/avi.jpg)