Search Unity

Programmatically get StreamingAsset file extension

Discussion in 'Scripting' started by flip_the_unflappable, Feb 4, 2021.

  1. flip_the_unflappable

    flip_the_unflappable

    Joined:
    Jul 9, 2020
    Posts:
    11
    Greetings, I have looked through the docs and forums about StreamingAssets, but have not found a solution to this problem.

    Let's say I want to enable users to add assets to my custom game object via the StreamingAssets directory.

    If I add this to my MonoBehavior
    Code (CSharp):
    1. [Serializable] UnityEngine.Object m_streamableAsset;
    then users are able to drag and drop assets from the StreamableAssets directory onto my custom object via the Inspector.

    So far so good.

    But lets say I now want to know the file extension of this asset? How can I get that?
    Code (CSharp):
    1. UnityEngine.Object.name
    only returns the filename, without the extension.

    Code (CSharp):
    1. Path.GetFileName()
    can't find the file with extension unless I already know it.

    Is there a way to achieve this? A different class besides
    Code (CSharp):
    1. UnityEngine.Object
    that I should use?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    I don't think there's a perfect solution here using the vanilla editor. Creating a custom editor would allow you to intercept the data coming from the drag and drop, which should give you a more detailed reference to the asset(s) being dragged and the data you need.

    A less perfect solution would be to compile a list of all assets in the StreamingAssets folder, and compare the name of your Object to the name from the list. This would require everything to be uniquely named, or a way to gather context in another way, like
    Object texture;
    must be in the Textures subfolder or something.
     
  3. flip_the_unflappable

    flip_the_unflappable

    Joined:
    Jul 9, 2020
    Posts:
    11
    Yes, thank you for the response!
    I considered using Drag and Drop, but using a Custom Editor worked along with AssetDatabase:

    Code (CSharp):
    1. SerializedProperty streamingAsset = serializedObject.FindProperty("m_streamingAsset");
    2.             string fullPath = AssetDatabase.GetAssetPath(streamingAsset.objectReferenceValue);
    3.  
    Now of course it would be amazing if I could actually filter the values in the ObjectPicker when using
    Code (CSharp):
    1.  EditorGUILayout.PropertyField(streamingAsset);
    I know the API allows for a little bit of filtering, but it is not well documented nor is it feature rich enough to filter by directory or file extension... So looks like I gotta roll my own or find a plugin.