Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by DarkSlash · May 05, 2014 at 02:51 PM · spritetexture2dbackgroundspriterenderer

Sprite resized to whole screen

I need to create a gameObject from code, so I do this:

 GameObject background;
 background = new GameObject("background");
 background.AddComponent("SpriteRenderer");
 background.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("background");

No I need to scale that sprite to cover the whole screen but I can't do it. In Unity Scripting reference there's a section called "Sprite Size" that is not there! How can I achieve that?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
6
Best Answer

Answer by Romano · May 05, 2014 at 03:15 PM

I use a static class that I've written based on other Unity answers to deal with this. Here's my code (assumes an orthographic camera):

 #pragma strict
 
 public static class SpriteFunctions
 {
 
     // If fitToScreenWidth is set to 1 then the width fits the screen width.
     // If it is set to anything over 1 then the sprite will not fit the screen width, it will be divided by that number.
     // If it is set to 0 then the sprite will not resize in that dimension.
     function ResizeSpriteToScreen(theSprite : GameObject, theCamera : Camera, fitToScreenWidth : int, fitToScreenHeight : int)
     {
         var sr = theSprite.GetComponent(SpriteRenderer);
         if (sr == null) return;
      
         theSprite.transform.localScale = Vector3(1,1,1);
      
         var width = sr.sprite.bounds.size.x;
         var height = sr.sprite.bounds.size.y;
      
         var worldScreenHeight = theCamera.orthographicSize * 2.0;
         var worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;
          
          if (fitToScreenWidth != 0)
          {
             theSprite.transform.localScale.x = worldScreenWidth / width / fitToScreenWidth;    
          }
 
          if (fitToScreenHeight != 0)
          {
             theSprite.transform.localScale.y = worldScreenHeight / height / fitToScreenHeight;
          }
     }
 }

If this script (called SpriteFunctions) is in your scripts folder then all you need to do to resize the sprite is add this line to your code (cameraRef is a reference to the camera you want to fit the sprite to):

 SpriteFunctions.ResizeSpriteToScreen(background, cameraRef, 1, 1);

The " 1, 1" parameters are for if you want the image to be smaller than full size. (background, cameraRef, 2, 2) for example would give half the width and height.

Hope this helps!

Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image DarkSlash · May 05, 2014 at 08:47 PM 0
Share

You cant just do something like mySprite.width = Screen.width?

avatar image Romano · May 06, 2014 at 12:09 AM 0
Share

I don't think so, you don't seem to be able to manipulate the sprite any other way than with the scale. I think the section called sprite size in the documentation is a mistake that they've yet to delete. This is the closest thing that I've found. Being able to change the size of the sprite would make a whole lot of sense though, I hope they add it in Unity 5.

avatar image DarkSlash · May 06, 2014 at 03:33 PM 0
Share

Works perfect! I convert the code to C# in case someone want it!

     void ResizeSpriteToScreen(GameObject theSprite, Camera theCamera, int fitToScreenWidth, int fitToScreenHeight)
     {        
         SpriteRenderer sr = theSprite.GetComponent<SpriteRenderer>();
 
         theSprite.transform.localScale = new Vector3(1,1,1);
 
         float width = sr.sprite.bounds.size.x;
         float height = sr.sprite.bounds.size.y;
         
         float worldScreenHeight = (float)(theCamera.orthographicSize * 2.0);
         float worldScreenWidth = (float)(worldScreenHeight / Screen.height * Screen.width);
         
         if (fitToScreenWidth != 0)
         {
             Vector2 sizeX = new Vector2(worldScreenWidth / width / fitToScreenWidth,theSprite.transform.localScale.y);
             theSprite.transform.localScale = sizeX;
         }
         
         if (fitToScreenHeight != 0)
         {
             Vector2 sizeY = new Vector2(theSprite.transform.localScale.x, worldScreenHeight / height / fitToScreenHeight);
             theSprite.transform.localScale = sizeY;
         }
     }
avatar image TempestMia DarkSlash · Sep 24, 2015 at 01:17 AM 0
Share

This totally fixed my issue! Thanks for the original response + the C# version!

avatar image DarkSlash · May 06, 2014 at 03:39 PM 0
Share

Im trying to understand certain parts because I want not just to put the background in full screen but to make objects relative to windows screen (for mobile compatibility). So, why do you do this: **worldScreenHeight / Screen.height Screen.width and then why you set width like this: worldScreenWidth / width / fitToScreenWidth*?

avatar image Romano · May 06, 2014 at 06:06 PM 0
Share

So for the worldScreenHeight / Screen.height * Screen.width question... the first part worldScreenHeight / Screen.height is the screen height in world units divided by the screen height in pixels. I believe this gives you the correct ratio (or do I mean scale? I'm not good with maths stuff) to multiply the pixel screen width by to give you the screen width in world units.

The orthographicSize of the camera is deter$$anonymous$$ed by height, which is why worldScreenHeight is figured out before worldScreenWidth - you need that first to figure out the ratio (or whatever you call that magic number).

As for the worldScreenWidth/width/fitToScreenWidth question... I could probably have named things in that script a little bit better...

"width" refers to the sprite width in world units. You might want to do yourself a favour and rename that to spriteWidth (and spriteHeight). I'm going to do the same in my script.

worldScreenWidth refers to the screen width in world units.

So say the world screen width is 10 and the sprite width ("width") is 2.

10 divided by 1 is 10, i.e you can fit ten of the sprite in the width of the screen. So to fit to the screen you scale up the sprite by 10.

fitToScreenWidth is a variable that lets you scale the sprite up to less than the screen width. So if you DO want it to be scaled to the full screen width,

fitToScreenWidth should be 1. 10 / 1 / 1 is still 10. So the sprite is still scaled by 10 and still fits the screen width.

But if you just want it to scale to half the screen width, set fitToScreenWidth to 2.

10 / 1 / 2 = 5. The sprite is only scaled up by 5 on the x axis and therefore only fits half the screen width.

A huge chunk of my code for this script is from this guy: http://answers.unity3d.com/questions/620699/scaling-my-background-sprite-to-fill-screen-2d-1.html

I just made it a static class and messed around with it a bit. In the comments of the question he says you'd need to change some stuff to make it work for C#. I don't know how to do C# so I might not be the best person to help fix your problem with it.

I do notice though that you're using the class differently to me. You seem to have made it a component that youre adding to something.

If you leave the static class in your scripts folder all you need to do to resize the sprite is use one line of code:

SpriteFunctions.ResizeSpriteToScreen(background, cameraRef, 1, 1);

It's working pretty nicely in my current script.

Good luck with it :)

Show more comments
avatar image
2

Answer by luislodosm · Apr 12, 2018 at 11:49 PM

With a perspective camera:

     public SpriteRenderer spriteRenderer;
     public Camera camera;
 
     void OnGUI()
     {
         float spriteHeight = spriteRenderer.sprite.bounds.size.y;
         float spriteWidth = spriteRenderer.sprite.bounds.size.x;
         float distance = transform.position.z - camera.transform.position.z;
         float screenHeight = 2 * Mathf.Tan(camera.fieldOfView * Mathf.Deg2Rad / 2) * distance;
         float screenWidth = screenHeight * camera.aspect;
         transform.localScale = new Vector3(screenWidth / spriteWidth, screenHeight / spriteWidth, 1f);
     }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jamez0r · Feb 15, 2021 at 01:03 AM 0
Share

Thanks @luislodosm - saved me a lot of headache trying to figure this exact calculation out!

avatar image
0

Answer by ATLGAN · May 18, 2021 at 08:19 AM

Working perfectly but there is a small problem. I using this method for my sprite, it's good for y axis but doesn't fit correctly on x axis.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

25 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Can I create a sprite at runtime? 3 Answers

How do I make individual pixels of my objects sprite change color/disappear? 1 Answer

Change SpriteRenderers Texture2D in runtime 1 Answer

How to get Sprite color palette 1 Answer

How do I fill a Texture2D with pixels and display a sprite with that texture using script? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges