ひつじTips

技術系いろいろつまみ食います。

[Unity]Texture2Dのサイズを変更する方法

UnityのTexture2Dのサイズを変更したいとき「Texture2Dにresize関数がある!これで勝つる!」と思ったら,灰色になる(=色がなくなる)の,あるあるですよね.

Texture2Dのサイズを変更するのに,ググると以下の2つぐらいが出るかと思います.

light11.hatenadiary.com

kan-kikuchi.hatenablog.com

1つ目はRenderTextureを経由してリサイズする方法,2つ目はピクセル単位でCPUでループ回してサイズを変える方法,だ思うのですが,

今回はもう1つの(もっとカンタンではなかろうかと思われる)方法あったよ,というお話です.

結論

Graphics.ConvertTexture関数を使えばできます.

docs.unity3d.com

第一引数のsrcの方にサイズを変更したい元テクスチャを入れて,第二引数のdstには変更したいサイズのテクスチャを入れます.

例えば,このような関数を作れば便利に使えるかなと思います.

    static Texture2D ResizeTexture(Texture2D srcTexture, int newWidth, int newHeight) {
        var resizedTexture = new Texture2D(newWidth, newHeight);
        Graphics.ConvertTexture(srcTexture, resizedTexture);
        return resizedTexture;
    }

ただし,テクスチャのコピーになるので,パフォーマンスがシビアなところではご使用にお気をつけください.

具体例

例えば,以下のようなC#スクリプトで挙動を確認します.

これを適当なGameObjectにつけて実行すると,Spaceを押下したときに,テクスチャのWidth/Heightをプラス100してサイズ変更し,インスペクタで設定したオブジェクトのマテリアルのテクスチャを更新します.

public class TextureResizer : MonoBehaviour {
    public Texture2D targetTexture;
    public MeshRenderer targetMeshRenderer;

    private Material targetMaterial;

    void Start() {
        Debug.Log(string.Format("Width: {0}, Height: {1}", 
                                                 targetTexture.width, targetTexture.height));
        targetMaterial = targetMeshRenderer.material;
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            targetTexture = ResizeTexture(targetTexture, 
                                                            targetTexture.width + 100, 
                                                            targetTexture.height + 100);
            targetMaterial.SetTexture("_MainTex", targetTexture);
            Debug.Log(string.Format("Width: {0}, Height: {1}", 
                                                     targetTexture.width, targetTexture.height));
        }
    }

    static Texture2D ResizeTexture(Texture2D srcTexture, int newWidth, int newHeight) {
        var resizedTexture = new Texture2D(newWidth, newHeight);
        Graphics.ConvertTexture(srcTexture, resizedTexture);
        return resizedTexture;
    }
}


これを実行したときのテクスチャをUnityEditor上で確認すると,もともと256x256だったのですが,356x356に変わっていることがわかります.

f:id:mu-777:20200222185048p:plain


また,コンソール出力を見ると,ちゃんとWidth/Heightが100ずつ増えていることがわかります.

f:id:mu-777:20200222014108p:plain