1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AssetDatabase.LoadAssetAtPathの引数のassetPathを拡張子なしにしたいときの実装方法

Posted at

本記事について

ResourcesもAssetBundleも拡張子ないのがデフォルトだが、AssetDatabase.LoadAssetAtPathでは拡張子あり。
interface切って疎結合にする際に拡張子なしで統一したほうが良いので、タイトルのような需要が生まれる。

実装

BuiltinResources.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
# if UNITY_EDITOR
using UnityEditor;
# endif

public class BuiltinResources
{
    static readonly string ResourcesPath = "Assets/Sample/BuiltinResources/";

    public T Load<T>(string path) where T : UnityEngine.Object
    {
        T asset = null;

# if UNITY_EDITOR
        string dirPath = ResourcesPath + Path.GetDirectoryName(path);
        string fileName = Path.GetFileName(path);
        string[] names = Directory.GetFiles(dirPath, fileName + "*", SearchOption.TopDirectoryOnly);
        string assetPath = "";
		for (int i = 0; i < names.Length; i++)
		{
            string n = names[i];
            if (n.Contains(".meta"))
            {
                continue;
            }
            assetPath = n;
            break;
		}

        if (assetPath == "")
        {
            throw new Exception("asset not found path " + path);
        }

        asset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
# endif
        return asset;
    }
}

使用する際はエディターなのでDirectory.GetFilesでファイルの情報が取ってこれる。
そこから拡張子を取得する。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?