Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

unity 2d

/* How to scale any asset to your screen size:
Set up:
- Click on your asset or sprite in the project folder and change the
	'Pixels per Unit' from the default 100, to the resolution of the sprite.
    (e.g. 64, 128, 256, etc.) Then click 'Apply' at the bottom right.
- Attach the first script to the main camera (or an object that doesn't 
	effect the world).
- Attach the second script to the asset/sprite you want to scale.
*/

// First script
using UnityEngine;
public class ScreenSize : MonoBehaviour
{
    public static float GetScreenToWorldHeight
    {
        get
        {
            Vector2 topRightCorner = new Vector2(1, 1);
            Vector2 edgeVector = Camera.main.ViewportToWorldPoint(topRightCorner);
            var height = edgeVector.y * 2;
            return height;
        }
    }
    public static float GetScreenToWorldWidth
    {
        get
        {
            Vector2 topRightCorner = new Vector2(1, 1);
            Vector2 edgeVector = Camera.main.ViewportToWorldPoint(topRightCorner);
            var width = edgeVector.x * 2;
            return width;
        }
    }
}

// Second script
using UnityEngine;
public class Scaler : MonoBehaviour
{
	void Start()
	{
    	float width = ScreenSize.GetScreenToWorldWidth;
    	transform.localScale = Vector3.one * width;
	}
}

//=============================================================================
// Edit: After messing around with this a bit, this is a way to automatically
//		 fit a sprite to the monitors X and Y screen dimensions.

// Second script (NEW)
using UnityEngine;
public class Scaler : MonoBehaviour
{
	void Start()
	{
    	// Declare width and height values
    	float width = ScreenSize.GetScreenToWorldWidth;
    	float height = ScreenSize.GetScreenToWorldHeight;
        
        // Check if the window is landscape
        if (width > height)
        {
            transform.localScale = Vector3.one * height;
        }

		// Check if the window is portrait
        if (height > width)
        {
            transform.localScale = Vector3.one * width;
        }
        
        // Check if the length of the window edges are equal
        if (width == height)
        {
            transform.localScale = Vector3.one * ((width + height) / 2);
        }
	}
}

// Sorry for the long answer ;)
Source by medium.com #
 
PREVIOUS NEXT
Tagged: #unity
ADD COMMENT
Topic
Name
1+8 =