Search code examples
c#unity-game-engine

What is the correct file path in Unity when you drag a folder into the unity project?


I am trying to read a file at game start and I keep getting a file not found error. In my project, I have the following directory structure:

Assets
+ - Resources
    + - Dictionary
        + - English
          + - words.txt

I try and access words.txt with the following code:

   private void LoadDictionary(string resourcePath)
    {
        dictionaryWords = new HashSet<string>();
        TextAsset dictionaryFile = Resources.Load<TextAsset>(resourcePath);

        if (dictionaryFile != null)
        {
            string[] words = dictionaryFile.text.Split(new[] { '\r', '\n' }, System.StringSplitOptions.RemoveEmptyEntries);

            foreach (var word in words)
            {
                dictionaryWords.Add(word.Trim().ToLower());
            }
        }
        else
        {
            Debug.LogError("Dictionary file not found at: " + resourcePath);
        }
    }

Then call it like this:

 public const string dictionaryFile = "Resources/Dictionary/English/words.txt";

 LoadDictionary(dictionaryFile);

but it cannot access the file. What am I missing from my file path? I also tried "Assets/Resources/Dictionary/English/words.txt"


Solution

  • Do not include the Assets or Resources portion of the path.

    Docs:

    The path does not need to include Assets and Resources in the string, for example loading a GameObject at Assets/Guns/Resources/Shotgun.prefab would only require Shotgun as the path.

    In your case the path is likely: Dictionary/English/words

    That being said, it is better to create a TextAsset field in your script, and drag the file reference into it.

    [SerializeField] private TextAsset wordDictionary;
    

    Files that are in the Resources folders will not retain the same folder structure path in the build (in the sense of general IO operations, such as those found in System.IO namespace). All assets in the Resources folders are compiled when building.

    Docs:

    All assets found in the Resources folders and their dependencies are stored in a file called resources.assets.

    If an asset is already used by another level it is stored in the .sharedAssets file for that level.