- Home /
Collider2D Resize Based on Sprite Using Generics
Generics are great, but sometimes they're puzzles to code. This is one of those cases, when the answer might be obvious, but I can't find it. So... That's my problem:
The Problem
I need to resize LOTS of BoxCollider2Ds, CircleCollider2Ds, etc... During runtime, but it would take time to write it on all of them, so I've decided: I'll make an Extension via Generics!
Oh well, the world was all in colors, 'till I tested it. The Colliders2D were not being resized!
But why? Because I am using a Generic where T: Collider2D? Because I can't access the size component without a temp? Because I can't set Collider2D.bounds?
The Script
public static void RescaleToSprite<T> (this T collider) where T: Collider2D
{
if (collider is BoxCollider2D)
{
Debug.Log("Workin'");
Vector2 newSize = collider.gameObject.GetComponent<SpriteRenderer>().sprite.bounds.size;
var tmp = collider.bounds;
tmp.size = newSize;
}
}
Well... If someone knows what am I doing wrong, please tell me.
Thanks in advance.
I deleted my answer, cuz it was based on reading your code wrong.
var tmp = collider.bounds;
tmp.size = newSize;
//you want to adjust the BoxCollider2D size. Not it's bound's member's size.
BoxCollider2D tmp = collider;
tmp.size = newSize;
Answer by YoucefB · Oct 13, 2017 at 06:35 PM
You have to define the collider's type to access its properties:
public static void RescaleToSprite<T> (this T collider) where T: Collider2D
{
if (collider is BoxCollider2D)
{
Vector2 newSize = collider.gameObject.GetComponent<SpriteRenderer>().sprite.bounds.size;
(collider as BoxCollider2D).size = newSize;
}
}
Thanks for taking your time to solve my problem. It works.