0
\$\begingroup\$

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);
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Use AddComponent<PolygonCollider2D>() to generate collider runtime.

void Start () 
{
    gameObject.AddComponent<PolygonCollider2D>(); //collider for itself
    obj2.AddComponent<PolygonCollider2D>(); //collider for other object
}

enter image description here

SetPath() is used to manipulate vertex runtime.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .