Reputation: 7919
i create an gameobject in runtime and then add it a BoxCollider2d
Component like below:
GameObject card = new GameObject("card");
card.AddComponent<BoxCollider2D>();
card.GetComponent<BoxCollider2D>.size = new Vector2(?);
in new vector2(?) i need a value that make box collider size exact same as card object size. the card has sprite so i try this :
card.AddComponent<SpriteRenderer>();
card.GetComponent<SpriteRenderer>().sprite = sprite
so i try like this ?
int cardWidth = (int)card.GetComponent<SpriteRenderer>().sprite.rect.width;
int cardHeight = (int)card.GetComponent<SpriteRenderer>().sprite.rect.height;
and then :
card.GetComponent<BoxCollider2D>().size = new Vector2(cardWidth, cardHeight);
this is my way i want to set size of collider to exact same as card object but it doesn't work. so please show me a way that i can set size of box collider same as card object.
Upvotes: 0
Views: 3340
Reputation: 7919
Finally i find the solution . the with and height of each sprit is 256px and my unit is 128 so 256/128=2
now my vector2 size is :
card.GetComponent<BoxCollider2D>.size = new Vector2(2,2);
and it's exact same as object size
Upvotes: 2