LoginSignup
7

More than 5 years have passed since last update.

【Unity】特定dir以下のファイルを一括で紐付けるレシピ【Editor拡張】

Posted at

UnityでObjectを紐付けるのが面倒

Unity上で画像やprefabを特定のObjectから使う場合、
Resources.LoadやAssetBundleなど色々な方法がありますが、
色んな都合で"まだ"使えないんだよなぁ…なんて場合もあります。
(将来的にAssetBundleにするし…とか?)
とりあえずササッと動くように…なんてpublicにしておいたら、

[クリエイティブ] : 画像追加しました。
[システム] : はーい
[システム] : (さてと…紐付け更新するか…)

スクリーンショット 2015-05-17 19.21.40.png

なんて事になったり。

そんな時にはコレ!

ボタンを押下したら一括で入れちゃえばいいじゃない!

Inspector上にボタンを作る
(Unity Inspector上にボタンを作るにはこれを参考にどうぞ)

GameImgHolder.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
using System.Linq;
#endif

public class GameImgHolder : MonoBehaviour {

    public List<Sprite> imgList;

#if UNITY_EDITOR
    [Button("SetupImg" , "Setup Image")]
    public int SetupImgButton;

    void SetupImg(){

        // path , imgdir
        string prefabPath = "Assets/Prefab/GameManager.prefab";
        string imgDir = "Assets/Images/Test";

        GameManager gm = AssetDatabase.LoadAssetAtPath(prefabPath , typeof(GameManager)) as GameManager;
        GameImgHolder imgHolder = gm.GetComponent<GameImgHolder>();

        // 各ファイルパス GUIDからを重複しないように取得
        var guids = AssetDatabase.FindAssets("" , new string[]{imgDir});
        var pathList = guids.ToList().Select(guid => AssetDatabase.GUIDToAssetPath(guid)).Distinct();

        // sprite load
        var sprites = pathList.Select(path => AssetDatabase.LoadAssetAtPath(path , typeof(Sprite)) as Sprite);
        imgHolder.imgList = sprites.ToList();

        // 変更があったことをUnityに知らせる必要があり、
        // そのため、このオブジェクトのダーティフラグをセットする
        EditorUtility.SetDirty(gm);
        AssetDatabase.SaveAssets();

        // // Hierarchy上に配置されているオブジェクトにも反映
        PrefabUtility.RevertPrefabInstance(GameManager.Instance.gameObject); 

#endif
}

こんな感じで使えます。

qiita_unity_ediror_button.mov.gif

この例ではSpriteでやりましたが、
TextAssetでもPrefab(GameObject)でもなんでも出来るので便利です。
自分で押してもいいですし、クリエイティブ側に押させてもいいですね。
(コリジョンには注意!)

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
7