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.
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. Unity - Scripting API: MonoBehaviour.Reset()
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.
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” 