2D - Scaling Sprites by Screen Resolution

Hello,

my problem is that my sprites doesn’t scale by the Screen Resolution. So how to do that?

  • Keyjin

My SpriteRenderer game object wasn’t scaling with my screen because I had added it as a child to the Canvas. By moving it outside of the Canvas, the sprite resized automatically with the screen. No scripts needed.

Once upon a time I created level editor for one my game(not in Unity) and as I remember I used next algorithm.

Let’s say you have default resolution 1024x768 (just for example). And you have done your scene with sprites and it looks perfect for 1024x768 resolution. Somewhere in the Start() function do this:

public int defaultWidth = 1024, defaultHeight = 768;
public Vector3 scale;

void Start() {
  scale = new Vector3(defaultWidth / screen.width, defaultHeight / screen.height, 1f);
}

Then u should do this for your sprites:

sprite.transform.scale = Vector3.Scale(sprite.transform.scale, scale);
sprite.transform.position = Vector3.Scale(sprite.transform.position, scale); //not sure that you need this

EDIT: this will work only at runtime, not sure how to do it in editor

thanks :slight_smile: but i have done my own solution

using UnityEngine;
using System.Collections;

public class TransformFormat : MonoBehaviour {

	private Object[] Sprites;
	private static Vector2 aspectRatio;

	// Use this for initialization
	void Start () {
		aspectRatio = AspectRatio.GetAspectRatio (Screen.width, Screen.height);
		
		Camera.main.orthographicSize = (1080 * (aspectRatio.y / 9f) / 2) / 100;
		Sprites = FindObjectsOfType (typeof(GameObject));
		foreach (GameObject Sprit in Sprites) {
			if (Sprit.GetComponent<SpriteRenderer> () && !Sprit.transform.parent) {
				Sprit.transform.localScale = new Vector3 (Sprit.transform.localScale.x * (aspectRatio.x / 16f), Sprit.transform.localScale.y * (aspectRatio.y / 9f), Sprit.transform.localScale.z);
				Sprit.transform.position = new Vector3 (Sprit.transform.position.x * (aspectRatio.x / 16f), Sprit.transform.position.y * (aspectRatio.y / 9f), Sprit.transform.position.z);
			}
		}
	}

	public static Vector2 getTransVel(Vector2 Velocity){
		aspectRatio = AspectRatio.GetAspectRatio (Screen.width, Screen.height);
		return new Vector2 (Velocity.x*(aspectRatio.x / 16f),Velocity.y*(aspectRatio.y / 9f));
	}
}