Search Unity

Change sprite texture size and position

Discussion in '2D' started by smelchers, Apr 14, 2015.

  1. smelchers

    smelchers

    Joined:
    Feb 22, 2015
    Posts:
    22
    Hello!

    I am changing a texture at runtime.

    I am using this code:

    cell.gameObject.GetComponentInChildren<SpriteRenderer>().sprite = Resources.Load("apple", typeof(Sprite)) as Sprite;

    However I have not found a way to set the size and position of the texture.
    The image is 256x256 pixels in size, and that is exactely the size that it is drawn onto the screen.
    I would like to have it drawn in a smaller size.

    Can somebody tell me how to change the size and preferrably also the position?

    Thank you.
    Susy
     
  2. originalterrox

    originalterrox

    Joined:
    Feb 6, 2015
    Posts:
    40
    yourgameobject.transform.scale = new vector3(2,2,1); should work.
     
  3. larku

    larku

    Joined:
    Mar 14, 2013
    Posts:
    1,422
    Almost. It'll be:

    For scale:

    Code (csharp):
    1. float newScale = 0.5f; // half scale
    2. yourGameObject.transform.localScale = new Vector3(newScale, newScale,1);
    For position:

    Code (csharp):
    1. float newX = 123.1f
    2. float newY = 321.5f
    3. float newZ = 1f
    4. yourGameObject.transform.position = new Vector3(newX, newY,newZ);
    But it is often better base the position and size from the current like so:

    Code (csharp):
    1. Vector3 newScale = yourGameObject.transform.localScale;
    2. // Lets keep the z scale since this is a sprite.
    3. newScale.x *= 0.5f; // half the scale
    4. newScale.y *= 0.5f; // half the scale
    5. yourGameObject.transform.localScale = newScale;
    6. //
    7. // Note, you can not do:
    8. //   yourGameObject.transform.localScale.x = someNewValue;
    9. // You must always set the entire Vector3 object like shown in the examples above.
    10. // The same applies for scale etc.
    11.  
    12. //
    13. //Similarly for position do:
    14. //
    15. Vector3 newPosition = yourGameObject.transform.position;
    16. // Lets keep the z position the same (for example)
    17. newPosition.x = 200f; // set it at 200.
    18. newPosition.y += 10f; // move it up 10
    19.  
    20. yourGameObject.transform.position = newPosition;
     
    yshilpi98 likes this.