When you create an object with polygon collider 2d from inspector, unity automatically generates polygon collider that approximately fits the sprite. My question is if there is a way to do that when creating an object from a script?
While searching for a solution I found that each sprite has a sprite mesh which has vertices. I tried setting those as a path for my collider, but the result is a mess: their order appears to be messed up.
My current code:
Sprite spr; // I get that in other part of the code
GameObject go = (GameObject)Instantiate(prefab, gameObject.transform);
go.GetComponent<SpriteRenderer>().sprite = spr;
go.GetComponent<PolygonCollider2D>().SetPath(0, spr.vertices);
There appears to be a somewhat good solution: add new polygon collider ( and remove the old one). When you add new collider with go.AddComponent<PolygonCollider2D>(); it will be generated to fit the mesh.
For anyone finding this, there is a better way than OP’s answer (sorry senpai).
// Store these outside the method so it can reuse the Lists (free performance)
private List<Vector2> points = new List<Vector2>();
private List<Vector2> simplifiedPoints = new List<Vector2>();
public void UpdatePolygonCollider2D(float tolerance = 0.05f)
{
polygonCollider2D.pathCount = sprite.GetPhysicsShapeCount();
for(int i = 0; i < polygonCollider2D.pathCount; i++)
{
sprite.GetPhysicsShape(i, points);
LineUtility.Simplify(points, tolerance, simplifiedPoints);
polygonCollider2D.SetPath(i, simplifiedPoints);
}
}
This way you don’t have to destroy / add a new PolygonCollider2D each time, plus the points List can be recycled for some free optimization.
Thanks to @empath for pointing me towards LineUtility.Simplify!