LoginSignup
21
17

More than 5 years have passed since last update.

Unityのファイルインポート時に任意の処理を走らせる。

Posted at

概要

Unityプロジェクトにファイルを追加する際に、毎回決まって行なう作業とかありませんか?

その作業、インポート時のイベントをフックすることでひょっとしたら自動化できるかも!
というお話を綴ります。

手順

1. スクリプトファイル作成

ss_120.png
Editorフォルダの下に任意のクラスを作ってね!

2. コード記述

ImportProcessor.cs
using UnityEditor;  //!< UnityEditorを追記してね
using UnityEngine;
using System.Collections;

public class ImportProcessor : AssetPostprocessor   //!< AssetPostprocessorを継承するよ!
{

}

ベースはこれで完成!
とっても簡単ね!

続きは使用例とリファレンスを参照してね!

使用例

テクスチャインポート時に Generate Mip Maps を無効化する

テクスチャのインポートをフックする場合は OnPreprocessTexture() または OnPostprocessTexture(Texture2D) を使うよ。

サンプルコード

using UnityEditor;  // UnityEditorを追記してね
using UnityEngine;
using System.Collections;

public class ImportProcessor : AssetPostprocessor   //!< AssetPostprocessorを継承するよ!
{
    void OnPreprocessTexture()
    {
        Debug.Log( "# テクスチャがインポートされるよ!" );

        // インポート時の設定に手を加える場合は assetImporter にアクセスするよ
        TextureImporter ti = assetImporter as TextureImporter;

        ti.mipmapEnabled = false;   // MipMap生成を無効化!
    }
}

インポートするファイルに Thumbs.db が含まれていたら削除する

もっとざっくり、すべてのインポート結果(削除や移動も)を監視することもできるよ!

サンプルコード

using UnityEditor;  // UnityEditorを追記してね
using UnityEngine;
using System.Collections;

public class ImportProcessor : AssetPostprocessor   //!< AssetPostprocessorを継承するよ!
{
    static void OnPostprocessAllAssets( string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths )
    {
        // インポートされたものリストをチェック
        foreach( string path in importedAssets )
        {
            Debug.Log( "# 「" + path + "」がインポートされたよ!" );

            // パス文字列に thumbs.db が含まれていたら削除!
            if( path.ToLower().IndexOf( "thumbs.db" ) >= 0 )
            {
                if( AssetDatabase.DeleteAsset( path ) )
                {
                    Debug.Log( "# thumbs.dbを削除したよ! (" + path + ")" );
                }
            }
        }
    }
}

参考

21
17
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
21
17