LoginSignup
9
11

More than 5 years have passed since last update.

Unityでビルド時の画像差替

Last updated at Posted at 2014-03-29

iOSアプリで画像を綺麗に表示するのにウェブテクノロジのClear PVRTCを利用しています。
開発中はPNGを利用しており、PVRTCは別途用意し、ビルド時に差し替えています。
差替方法として、依存関係を取得しPNGとPVRのGUIDを置換するようにしました。

同一フォルダにpngと差し替え用のpvrがあると過程したSample

TextureConvert
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

public class TextureConvert {

    public TextureConvert(string[] paths){
        AssetDatabase.StartAssetEditing();
        TextureDependenciesConvert(paths);
        AssetDatabase.StopAssetEditing();
    }

    string[] convertExtension = new string[]{ 
        ".unity",
        ".prefab",
        ".mat",
        ".asset",
    };

    Dictionary<string,string> GetConvertPath(string _path){

        Dictionary<string,string> convertList = new Dictionary<string,string>();

        foreach(string path in AssetDatabase.GetDependencies(new string[]{_path})){
            if (Path.GetExtension(path) == ".png"){ 
                string pvrPath = Path.ChangeExtension(path,".pvr");
                if (!string.IsNullOrEmpty(pvrPath) && File.Exists(pvrPath) && path != pvrPath){
                    convertList.Add(
                        AssetDatabase.AssetPathToGUID(path),
                        AssetDatabase.AssetPathToGUID(pvrPath)
                    );
                }
            }
        }
        return convertList;
    }

    void TextureDependenciesConvert(string[] paths){

        foreach(string path in AssetDatabase.GetDependencies(paths)){

            Dictionary<string,string> convertList = GetConvertPath(path);
            if (convertList.Count == 0) continue;

            string ext = Path.GetExtension(path);
            if (convertExtension.IndexOf(ext) > 0){

                StreamReader sr = new StreamReader(path,System.Text.Encoding.ASCII);
                string s = sr.ReadToEnd();
                sr.Close();

                StringBuilder sb = new StringBuilder(s);
                foreach(KeyValuePair<string,string> x in convertList){
                    sb.Replace(x.Key, x.Value);
                }
                if (s != sb.ToString()){
                    StreamWriter sw = new StreamWriter(path,false,System.Text.Encoding.ASCII);
                    sw.Write(sb.ToString());
                    sw.Close();
                    sw = null;
                }
                s = null;
                sr = null;
                sb = null;
            }
        }
    }
}

Unityでは直接ファイルのGUIDを書き換えるドキュメントは見た事がないので、バージョン変わると出来なくなるかもしれません。

9
11
0

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
9
11