[unity]絶対パスと Assets パスの変換メソッド

unity では Assets 以下に必要なファイルを全て入れることでプロジェクトを管理します。
AssetDatabase のパスもそれに倣い、Assets からの相対パスで場所を示します。

Assets/Scripts/Sample.cs

ところが、C# に元々あるファイルクラス(System.IO.Directory、System.IO.File、System.IO.Path など)はディスクの絶対パスで指定する必要があります。
Windows の場合ディレクトリ連結文字列が / → \ に変化するので、更に混迷します…。

D:\games\test\Assets\Scripts\Sample.cs

Path.Combine は便利だけど、連結文字列が / と \ 混在になったりする

Unity Editor 機能を作成していると、このどちらにもアクセスする事があるので、パスの表記方法は行ったり来たり。
その度に Replace コマンドを羅列しまくるのがちょっと不毛かな…と感じたので、string 拡張機能としてこれを実装してみることにします。

public static class stringExtension
{
    /// <summary>
    /// 絶対パスから Assets/ パスに変換する
    /// </summary>
    public static string AbsoluteToAssetsPath(this string self)
    {
        return self.Replace("\\", "/").Replace(Application.dataPath, "Assets");
    }

    /// <summary>
    /// Assets/ パスから絶対パスに変換する
    /// </summary>
    public static string AssetsToAbsolutePath(this string self)
    {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
        return self.Replace("Assets", Application.dataPath).Replace("/", "\\");
#else
        return self.Replace("Assets", Application.dataPath);
#endif
    }
}

string path = "Assets/Scripts/Sample.cs";
Debug.Log(path.AssetsToAbsolutePath()); // D:\games\test\Assets\Scripts\Sample.cs
Debug.Log(path.AbsoluteToAssetsPath()); // Assets/Scripts/Sample.cs

自分が作成したパスに Assets という文字列があると誤動作するので注意してください。
(厳密にチェックすることもできますが、長たらしくなるので…)

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA