LoginSignup
4
3

More than 5 years have passed since last update.

Unity エディタ拡張内で生成したテクスチャをPNG形式でAssetDatabase内に保存する

Last updated at Posted at 2016-12-23

はじめに

PLAY Animation Importer for Unity にて、「取り込んだテクスチャファイルの形式が *.asset になっているが、PNG 形式にしてほしい」という要望を頂いたので対応してみました。
ざっとネット検索してもドンピシャな方法を書いているページが見当たらなかったのですが、一応可能みたいですのでここにメモを残しておきます。

コード

Before
// pathTextureInAsset にテクスチャの保存先のファイル名(例: "Assets/textures/fooBarTexture.asset")が入っていると想定
// width, height にそれぞれ縦横サイズ、bytes に画像のバイト列が入っていると想定
var texture = new Texture2D(width, height, TextureFormat.ARGB32, false, false);
texture.LoadRawTextureData(bytes);
texture.Apply(true, true);
AssetDatabase.CreateAsset(texture, pathAsset);
// texture をマテリアルから参照
After
// pathTexturePngInAsset にテクスチャの保存先のPNGファイル名(例: "Assets/textures/fooBarTexture.png")が入っていると想定
// width, height にそれぞれ縦横サイズ、bytes に画像のバイト列が入っていると想定
var texture = new Texture2D(width, height, TextureFormat.ARGB32, false, false);
texture.LoadRawTextureData(bytes);
texture.Apply(true, false); // 第2引数(makeNoLongerReadable) を false にしておかないとEncodeToPNG() に失敗するので注意

// PNG 画像を保存してインポートし直す
File.WriteAllBytes(pathTexturePngInAsset, textureOrg.EncodeToPNG());
AssetDatabase.ImportAsset(pathTexturePngInAsset);
var texturePng = AssetDatabase.LoadAssetAtPath(pathTexturePng, typeof(Texture2D)) as Texture2D;
// texturePng をマテリアルから参照
4
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3