Text files not used when game is built

using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;

public class cemetary0 : MonoBehaviour {
    public string txt = "";
    static string path = "Assets\\Text\\cemetary0.txt";
    StreamReader script = new StreamReader(path);
    string line;
    void Start () {
        line = script.ReadLine();
    }
    private void narrate()
    {
        txt = line;
        line = script.ReadLine();
        i++;
        if (i == 4)
        {
            txt = "";
            CancelInvoke();
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject == player)
        {
            InvokeRepeating("narrate", 0, 2F);
        }
    }
    private void OnGUI()
    {
        if (x)
        {
            GUIStyle myStyle = new GUIStyle(GUI.skin.button);
            myStyle.fontSize = 28;
            Font myFont = (Font)Resources.Load("Fonts/comic", typeof(Font));
            myStyle.font = myFont;
            GUI.color = Color.white;
            GUI.Label(new Rect(0, Screen.height - 100, Screen.width, 100), txt, myStyle);
        }
    }
}

In short, I’m outputting text from a text file to be used as subtitle/narration.
The problem comes when I build the game, into a separate folder, everything works except for the text.
Is there any work around or solution to this?
Any help is appreciated

Your asset folder doesn’t exist anymore when you build the game, so looking for stuff in there by path won’t work. Except, if you use the StreamingAssets folder.

Anything that goes in StreamingAssets is copied as-is, without any processing, from your assets folder to the build folder. So you want to put all of the data you want to read as a file in StreamingAssets, and reference it through Application.streamingAssetsPath.

An alternative is to just have a public field of the type TextAsset. That type allows you to put a .txt file or similar directly on a MonoBehaviour, and not have to use a string reader API to get the text.

2 Likes

This.

There is also the Resources folder in which everything within the folder is built in with the game and can be accessed using Resources.Load(“someRelativePath”);