Skip to content

Instantly share code, notes, and snippets.

@jrunestone
Last active July 19, 2016 16:25

Revisions

  1. Johan Johansson renamed this gist Jul 19, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. Johan Johansson created this gist Jul 19, 2016.
    26 changes: 26 additions & 0 deletions unity-keep-texture-scale
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    using UnityEngine;
    using System.Collections;

    [ExecuteInEditMode]
    public class QuadTextureScaler : MonoBehaviour
    {
    private Renderer rend;
    private float textureWidthInUnits;
    private float textureHeightInUnits;
    private float pixelsPerUnit;

    private void Start() {
    rend = GetComponent<Renderer>();

    Texture texture = rend.material.mainTexture;

    pixelsPerUnit = Screen.height / (Camera.main.orthographicSize * 2);

    textureWidthInUnits = texture.width / pixelsPerUnit;
    textureHeightInUnits = texture.height / pixelsPerUnit;
    }

    private void Update () {
    rend.material.mainTextureScale = new Vector2(transform.localScale.x / textureWidthInUnits, transform.localScale.y / textureHeightInUnits);
    }
    }