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

Unityでファイルパス取得したり、c#のファイルパス取得したり、したり。

Posted at

初めに

開発していて独自のファイルをセーブしたり、ロードしたりする様な事があると思います。
僕の場合は、josnファイルで独自のデータをセーブして使ったりしてました。
その際にファイルのパスを調べてたり、ファイル名を調べたりする方法調べたものをまとめました。

シーンデータのパスを知りたい

    for( int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCount; ++i )
    {
        var path = SceneManager.GetSceneAt( i ).path;
        var fileNamepath = System.IO.Path.GetDirectoryName(path);
    }

上記でやっているのは読み込まれているシーンのパスを取得してパスのみ取得してます。
Assets\Scenes\hoge.unity
を取得してから
Assets\Scenes\のパスのみ取得する感じです。

AssetDatabase.GetAssetPath使ってパス取得

unityの機能で取得
自分の環境ではinspectorにTextAssetを指定できる場所を作って、そのファイルのパスを取得するのに使いました。
image.png

    var tex = EditorGUILayout.ObjectField("hoge", null, typeof(TextAsset), true) as TextAsset;
    var path = AssetDatabase.GetAssetPath(tex);

hogeにinstanceIDやassetObjectを入れて取得する方法
フルパスで帰ってきます。

いつも通り、先人の方がきれいにまとめてくれている

CreateInstanceで呼んであげると複数起動できるみたい

ついでにsaveの機能も。。きれいにまとまっている

最後に

ファイルパスを取得して最後のファイル名を追加して保存しようと思いよくやるのは
ファイルパス
Assets\Scenes
ファイル名
hoge.unity

上の二つをくっつけてやると
Assets\Sceneshoge.unity と自分が意図した位置にデータを保存すのに失敗します。
ちゃんとファイルパスの最後に"/"が入っていなかったら入れて使ってあげましょ。

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