简体   繁体   中英

How to put text file content to dictionary c# unity

I have a few text files with phrases in them(answers).In a text file for example I have 150 phrases.I am working on a fishing game.After you catch a fish, a reply appears(which comes from the text file) and appears in the middle of the screen.I thought that if I put my text file in the Assets folder then everything will be fine.But no!!! :(

Here is my code where I return my line(answer):

public string filename333 = "try.txt";

public string getRandomMessagefromRechin()
{

    var sr = new StreamReader(Application.dataPath + "/" + fileName1);
    var fileContents = sr.ReadToEnd();
    sr.Close();
    var mydata = fileContents.Split("\n"[0]);
    var myrandom = Random.Range(1, mydata.Length);
    return mydata[myrandom];

}

On PC , when i hit PLAY button , it s working fine,here is an image:

游戏

Sorry for the text , it's a random line from my text file.The problem is after I build the project on a tablet or android phone. The answers from my text files are not showing on my screen. I want to try another method with dictionaries or with a list of strings, but how can I put 150+ lines on a list from the text in a file?

I have another questions:

1.Why isn't my method working?(I suppose that my text files aren't being built, or aren't put in the right folder of the project)

2.Is another method which I can try to load my lines(answers)?

3.As this problem, I have another scene.After you catch a gold fish, a transition appears(screen go black, then screen goes back to normal) and a wheel of luck appears when u can play, like a roulette.This scene isn't loading on my android devices. Why?

It needs to be in the Resources folder. Unity will treat it as a "TextAsset". It will be readonly once you build.

You will want to use a function like this to split the contents of the file on New Lines and return a list of strings.

private List<string> TextAssetToList(TextAsset ta) {
    return new List<string>(ta.text.Split(System.Environment.NewLine));
}

You will also need to load it like other resources

TextAsset myTxt = Resources.Load("try") as TextAsset;
List<string> strLines = TextAssetToList(myTxt);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM