Search Unity

BoxCollider2D is attached with the wrong size

Discussion in 'Scripting' started by Max_power1965, Aug 31, 2017.

  1. Max_power1965

    Max_power1965

    Joined:
    Oct 31, 2013
    Posts:
    127
    Hello,
    I have a simple script which at the Awake function to create by code a SpriteRenderer and a BoxCollider2D, the problem is that both the SpriteRenderer and the BoxCollider2D are attached with the wrong size, the size of the box collider is 1.23 for both X and Y instead of the default 1 value. I know I can change the value in the code to match the size of 1 in both X and Y, but I want to know why are they both generated with the wrong values?

    This is the code to generate the SpriteRenderer and the BoxCollider2D:

    Code (CSharp):
    1. void Awake()
    2.     {
    3.         Sprite cellBackground = Resources.Load(Constants.Resurces.CELL_BACKGROUND, typeof(Sprite)) as Sprite;
    4.         Assert.IsTrue(cellBackground != null,"ERROR: the cellBackground " + Constants.Resurces.CELL_BACKGROUND + " has not been found");
    5.         _spriteRend = gameObject.AddComponent<SpriteRenderer>();
    6.          if (_spriteRend.sprite == null)  _spriteRend.sprite = cellBackground;
    7.      
    8.          gameObject.AddComponent<BoxCollider2D>();
    9.     }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,751
    I think when the BC2d is added Unity looks for a sprite renderer and sets the BC2d to match it.

    Try reversing the order: add the BC2d first, then , see if that's true.

    There may be other factors in play, such as if the scaling of the current object is not Vector3.one.
     
  3. Max_power1965

    Max_power1965

    Joined:
    Oct 31, 2013
    Posts:
    127
    Yes, actually also the sprite render has the problem and is added before the BC2d, and even if I set the scale of the SpriteRenderer to 1 and then add the BC2d, the BC2d has the same wrong scale.

    Maybe the scale of the object is the problem, in fact, the scale is less the 0, but anyway I don't get why the default value is 1.23...
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,751
    Generally speaking this isn't a Good Thing(tm). You should consider fixing that first.
     
  5. Max_power1965

    Max_power1965

    Joined:
    Oct 31, 2013
    Posts:
    127
    Yes, I know it, the assets are generated and scaled programmatically to fit the size of the screen. I maybe could add them to a parent game object and scale it instead of scale all of them, but still, the problem remains