title: Changing Sprite and keeping the same size
body: <p>I'm writing a game using the 2d features of unity.</p>
  
  <p>I'm designing a sort of inventory for the player character, and I have a gameobject with a number of placeholder images inside it. The intention is that when I actually load this gameobject, I'll replace the sprites of the placeholder images and I'll display what I want.</p>
  
  <p>My issue is that when I change the sprite using code like this</p>
  
  <pre><code>    var ren = item1.GetComponentInChildren&lt;SpriteRenderer&gt;();
  
  ren.sprite = Resources.Load&lt;Sprite&gt;("DifferentSprite");
  </code></pre>
  
  <p>The image loaded is correct, however the scaling applies to the new sprite. The issue is that these sprites have all different sizes. So whilst the original placeholder image takes up a small square, the replacement might be tiny or massive enough to cover the whole screen depending on how the actual png was sized.</p>
  
  <p>I basically want the sprite to replace the other and scale itself such that it has the same width and height as the placeholder image did. How can I do this?</p>
  
  <p>EDIT - I've tried playing around with ratios. It's still not working perfectly, but its close.</p>
  
  <pre><code>    var ren = item1.GetComponentInChildren&lt;SpriteRenderer&gt;();
  
      Vector2 beforeSize = ren.transform.renderer.bounds.size;
  
      ren.sprite = Resources.Load&lt;Sprite&gt;("Day0/LampOn");
  
      Vector2 spriteSize = ren.sprite.bounds.size;
  
      //Get the ratio between the wanted size and the sprite's size ratios
  
      Vector3 scaleMultiplier = new Vector3 (beforeSize.x/spriteSize.x, beforeSize.y/spriteSize.y);
  
      //Multiple the scale by this multiplier
      ren.transform.localScale = new Vector3(ren.transform.localScale.x * scaleMultiplier.x,ren.transform.localScale.y * scaleMultiplier.y);
  </code></pre>