UnityのTexture2Dのサイズを変更したいとき「Texture2Dにresize関数がある!これで勝つる!」と思ったら,灰色になる(=色がなくなる)の,あるあるですよね.
Texture2Dのサイズを変更するのに,ググると以下の2つぐらいが出るかと思います.
1つ目はRenderTextureを経由してリサイズする方法,2つ目はピクセル単位でCPUでループ回してサイズを変える方法,だ思うのですが,
今回はもう1つの(もっとカンタンではなかろうかと思われる)方法あったよ,というお話です.
結論
Graphics.ConvertTexture
関数を使えばできます.
第一引数のsrc
の方にサイズを変更したい元テクスチャを入れて,第二引数のdst
には変更したいサイズのテクスチャを入れます.
例えば,このような関数を作れば便利に使えるかなと思います.
static Texture2D ResizeTexture(Texture2D srcTexture, int newWidth, int newHeight) { var resizedTexture = new Texture2D(newWidth, newHeight); Graphics.ConvertTexture(srcTexture, resizedTexture); return resizedTexture; }
ただし,テクスチャのコピーになるので,パフォーマンスがシビアなところではご使用にお気をつけください.
具体例
これを適当な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に変わっていることがわかります.
また,コンソール出力を見ると,ちゃんとWidth/Heightが100ずつ増えていることがわかります.