• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
4
Question by Garth-Smith · May 20, 2013 at 07:08 PM · iosloadresourcesfiles

How do I get a list of filenames in a Resources folder?

Hello!

I have my level data stored in Unity/Assets/Resources/Levels

I can do Resources.LoadAll() to load everything from this folder, but that seems heavy-handed. I just want a list of filenames, so I know which files I can use Resources.Load() to load later.

How can I check if a file exists without loading the whole file?

Thanks for reading this!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

5 Replies

· Add your reply
  • Sort: 
avatar image
6

Answer by bfowle · May 20, 2013 at 07:22 PM

This can be achieved via native C# (`System.IO`):

 FileInfo[] fileInfo = levelDirectoryPath.GetFiles("*.*", SearchOption.AllDirectories);
                 
 foreach (FileInfo file in fileInfo) {
     // file name check
     if (file.Name == "something") {
         ...
     }
     // file extension check
     if (file.Extension == ".ext") {
         ...
     }
     // etc.
 }

You can filter out certain files and/or extensions based on the pattern in GetFiles() this example is checking all files in this dir.

Checking for a file existence is done w/the same library:

 if (File.Exists("/path/to/file.ext")) {}
Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Garth-Smith · May 20, 2013 at 08:51 PM 3
Share

Thanks for the response. I added a line to the beginning DirectoryInfo levelDirectoryPath = new DirectoryInfo(Application.dataPath); and the code works great in Unity Editor.

However this does not work on all platforms. On iOS, there does not appear to be a Resources directory under Application.dataPath. It appears Unity packs the entire resources directory into a single file /var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX/[name].app/Data/resources.assets so FileInfo does not work in this case.

avatar image bfowle · May 20, 2013 at 10:10 PM 1
Share

Ahh yes. I believe there is a workaround for this iOS case on this forum post.

avatar image Garth-Smith · May 20, 2013 at 10:26 PM 0
Share

It seems like I can actually get files in Assets/StreamingAssets through FileInfo, but Assets/Resources is still unavailable since it is not actually a directory on device.

So it seems like the two workarounds I have so far are to either put my files in StreamingAssets or check if Resources.Load() returns a null value.

avatar image yoyo · May 21, 2013 at 06:10 AM 2
Share

$$anonymous$$ind of a cheesy workaround, but could you generate a directory listing at build time and load it as a text asset?

avatar image Garth-Smith · May 22, 2013 at 12:50 AM 0
Share

yoyo, yes that is totally a valid workaround! I assume if I wanted to take that route then the BuildPipeline class is what I would use.

Show more comments
avatar image
5

Answer by Eric5h5 · May 21, 2013 at 08:30 AM

There is no Resources folder on any platform (and therefore no filenames); everything in Resources is compiled into a file called resources.assets.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Mayhem · Nov 15, 2015 at 04:45 AM 1
Share

This is .... taking the context after being compiled, Obviously the user in a round about way without knowing is asking.. How can i refer to the memory allocation of compiled resources using their filenames as allocation points

avatar image
1

Answer by astracat111 · Feb 23, 2018 at 10:25 AM

What you REALLY need to do is to put the resources you need to load inside your persistentDataPath folder UPON THE GAME STARTING. You can't use dataPath with all platforms, you can't use File.IO, so you will have to use Application.persistentDataPath.

I ran in to this problem recently with many of my files for my game. To get it working on Android platforms as well, I end up needing to take my files, put them in my SteamingAssets folder, then from there extract them to my dataPath folder. I use a library called SharpZip for this and use .tgz files (they're like .zip files but for Linux so I can get all this working on android). I create the .tgz file at start as a copy of the StreamingAssets path (which isn't accessible on android upon build as it's packaged into like a .apk).

I then extract that .tgz file into the persistentDataPath, esentially recreating my streamingAssets folder but at persistentDataPath at runtime. You have to check of course if there are already files there upon runtime as well so you don't overwrite your data files the second time you run the game.

PersistentDataPath is that path that you can access as a directory upon runtime on many different platforms including iOS, Android, Mac etc... Again, you can do this also with StreamingAssetsPath but it won't work on certain platforms.

Another quick tip: Make sure that you delete the files you need to with void OnApplicationExit() or whatever that method is.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SweatyChair · Oct 05, 2018 at 07:52 AM 0
Share

I think that should be an accepted answer, with a sample code and images would make this answer better.

avatar image Bunny83 · Oct 05, 2018 at 09:05 AM 0
Share

That's not really a solution, at least not a nice one. Unity can only load some assets from external sources. For example Unity can only load png or jpg at runtime dynamically. $$anonymous$$odels can't be loaded at all (not natively). persistentDataPath is just a storage location for data your game generates that should persist. Assets that are already shipped with your game shouldn't be "unpacked" into folder. This may apply when downloading AssetBundles from a server but not for normal assets.


As i said some assets can't actually be loaded. So they need to be imported in the editor and either shipped with your application or loaded on demand using AssetBundles.


Creatnig and deleting many larger files in the persistent data path that's not really necessary is a bad practise. For all mobile users that just means you use up the write cycles of the flash memory.


The next thing is if you ship the assets with your application, how do you actually access them in the first place in order to store them in the persistent data path?


Yes, using an archive would work but isn't really necessary since a build on mobile is already compressed.


I've actually posted a solution in my answer here. I've written the resourceDB several years ago which creates a list of all files in the resources folder(s) at edit time and stores that information for runtime use. The resources folder allows you to include any kind of asset. $$anonymous$$odels, textures, animations, prefabs, audioclips, ...

avatar image
1

Answer by Bunny83 · Feb 23, 2018 at 11:06 AM

Just for completeness I've created a "resource DB" two years ago which allows you to store all file information of assets inside resources folders in a "database" (ScriptableObject) which allows you to use that information at runtime. It only requires a "manual" update of the DB by selecting "Tools/Update ResourceDB". It will automatically create a scriptable object inside Assets/Resources/ and fill it with all the path information about all resources in any resources folder

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by YaVeTaL · Oct 15, 2014 at 03:08 PM

Found here , works fine for me so far.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System.IO;
  
 public class FileUtility {
   
     /// <summary>
     /// Determine whether a given path is a directory.
     /// </summary>
     public static bool PathIsDirectory (string absolutePath)
     {
         FileAttributes attr = File.GetAttributes(absolutePath);
         if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
             return true;
         else
             return false;
     }
  
  
     /// <summary>
     /// Given an absolute path, return a path rooted at the Assets folder.
     /// </summary>
     /// <remarks>
     /// Asset relative paths can only be used in the editor. They will break in builds.
     /// </remarks>
     /// <example>
     /// /Folder/UnityProject/Assets/resources/music returns Assets/resources/music
     /// </example>
     public static string AssetsRelativePath (string absolutePath)
     {
         if (absolutePath.StartsWith(Application.dataPath)) {
             return "Assets" + absolutePath.Substring(Application.dataPath.Length);
         }
         else {
             throw new System.ArgumentException("Full path does not contain the current project's Assets folder", "absolutePath");
         }
     }
  
     
     /// <summary>
     /// Get all available Resources directory paths within the current project.
     /// </summary>
     public static string[] GetResourcesDirectories ()
     {
         List<string> result = new List<string>();
         Stack<string> stack = new Stack<string>();
         // Add the root directory to the stack
         stack.Push(Application.dataPath);
         // While we have directories to process...
         while (stack.Count > 0) {
             // Grab a directory off the stack
             string currentDir = stack.Pop();
             try {
                 foreach (string dir in Directory.GetDirectories(currentDir)) {
                     if (Path.GetFileName(dir).Equals("Resources")) {
                         // If one of the found directories is a Resources dir, add it to the result
                         result.Add(dir);
                     }
                     // Add directories at the current level into the stack
                     stack.Push(dir);
                 }
             }
             catch {
                 Debug.LogError("Directory " + currentDir + " couldn't be read from.");
             }
         }
         return result.ToArray();
     }
 }

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Ocram1989 · Jul 20, 2016 at 02:01 PM 0
Share

i don't see anything...why?

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

23 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

iOS - Resources.LoadAsync is VERY slow on older iPads 0 Answers

Best way to manage hundreds of materials? 1 Answer

Altering prefab at runtime. Works in editor, not in build. 2 Answers

Resources Load array 0 Answers

Resources.Load renaming/moving resources. 0 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges