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);
Related
I have a Unity project which I want to work for both android and ios. I also have a csv file which I want to read during runtime. I tried the following code:
string basePath = Path.Combine(Application.persistentDataPath, $"{fileName}.csv");
if (File.Exists(basePath))
{
string[] rows = File.ReadAllLines(basePath);
foreach (string item in rows)
{
Debug.Log(item);
}
}
However, I don't know where to put the csv file for it to find it on persistentDataPath. And if I find the correct place, will it be the same on android and ios or do I need to save the file on more locations or folders?
Or do you have any other suggestions on how to store and then load a cvs for different platforms?
If you just want to read a .csv file that you deploy with your game, you could just place it into the Resources folders inside your Assets.
You could read it like this:
TextAsset file = Resources.Load(fileName) as TextAsset;
string content = file.ToString();
Note: fileName must be specified here without file extension.
If you want to modify the .csv file or perhaps make it available in Application.persistentDataPath, you can simply copy it to that location first. For later changes you can then access the file in persistentDataPath.
Self-Contained Example
A self-contained example could look something like this:
using System.IO;
using UnityEngine;
public class CSVFileManager : MonoBehaviour
{
void Start()
{
var fileName = "example";
var csvFileName = $"{fileName}.csv";
string basePath = Path.Combine(Application.persistentDataPath, csvFileName);
Debug.Log($"basePath = >>{basePath}<<");
if (!File.Exists(basePath))
{
TextAsset file = Resources.Load(fileName) as TextAsset;
string content = file.ToString();
File.WriteAllText(basePath, content);
}
else
{
//... work with the current file in persistentDataPath
}
}
}
Test
I tested it briefly on Mac, but it should work equally well on Android and iOS:
I have a JSON file which contains data for my Localization in my game. The file is stored in Application.persistentDataPath . I read in the documentation that the file is not deleted or overwritten when updating the game. Currently I launch the app and the file is there but when I add more content and send an update to save again, it only has the original content.
But is there a way to update this file when I update the game?
What if in the future I want to add more content to this JSON file, I would have to delete it and upload it again?
Any way to update and overwrite it?
private static void Request(string file)
{
var loadingRequest = UnityWebRequest.Get(Path.Combine(Application.streamingAssetsPath, file));
loadingRequest.SendWebRequest();
while (!loadingRequest.isDone)
{
if (loadingRequest.isNetworkError || loadingRequest.isHttpError)
{
break;
}
}
if (loadingRequest.isNetworkError || loadingRequest.isHttpError)
{
// Some error happened.
}
else
{
File.WriteAllBytes(Path.Combine(Application.persistentDataPath, file), loadingRequest.downloadHandler.data);
}
}
// Loads key from "StreamingAssets/language_data.json" file.
public static string LoadJson(string key)
{
Request("data.json");
var jsonPath = Path.Combine(Application.persistentDataPath, jsonFileName);
using (StreamReader r = new StreamReader(jsonPath))
{
var N = JSON.Parse(r.ReadToEnd());
string result = N[GetLanguage()][key];
return result;
}
}
I think the issue is the following:
You are only creating a file named data.json NOT languages_data.json!
In Request (you pass in "data.json") you copy
Application.streamingAssetsPath, file
to
Application.persistentDataPath, file
where file = "data.json"
Then in LoadJson you are trying to load values from
Application.persistentDataPath, jsonFileName
where - as to your comments - jsonFileName = "languages_data.json"
=> It is a different path!
In the Editor/on your PC you probably still have an old languages_data.json in the persistent data from some time ago. Therefore there is no error but it is also never updated. Delete the persistent/languages_data.json on your PC and it will throw a FileNotFoundException.
To solve this make 100% sure the file names are the same everywhere. The simplest fix code wise would be to simply rather use
Request(jsonFileName);
and make sure that jsonFileName matches the name of your existing file in StreamingAssets.
I am working in Windows 10 platform using c#. I'm developing a method that will monitor video files being created. I want to know when they are complete and when they are being created. The files are very large and so I think I should be able to get the size of the file and then 5 seconds later check to see if it has grown.
private void main()
{
string file = Path.Combine(roomPath, currentFile);
FileInfo fil = new FileInfo(file);
double previousSize = fil.Length;
Thread.Sleep(5000);
string file2 = Path.Combine(roomPath, currentFile);
FileInfo fil2 = new FileInfo(file2);
double currentSize = fil2.Length;
}
I expected to get a snapshot of the size of the file at 2 different instances but, although the file should be much larger after 5 seconds they are both the same.
I currently am making a UI for a note keeper and was just going to preview documents etc, but i was wondering what file type i would need to create if instead i wanted to do things like tag the file etc, preferably in c#, basically make my own evernote, how do these programs store the notes?
I dont know how to directly tag the file, but you could create your own system to do it. I mentioned two ways to do it:
The first way is to format the note's / file's contents so that there are two parts, the tags and the actual text. When the program loads the note / file, it seperates the tags and the text. This has the downside that the program have to load the whole file to just find the tags.
The second way is to have a database with the filename and it's associated tags. In this way the program doesn't have to load the whole file just to find the tags.
The first way
In this solution you need to format your files in a specific way
<Tags>
tag1,tag2,tag3
</Tags>
<Text>
The text you
want in here
</Text>
By setting up the file like this, the program can separate the tags from the text. To load it's tags you'd need this code:
public List<string> GetTags(string filePath)
{
string fileContents;
// read the file if it exists
if (File.Exists(filePath))
fileContents = File.ReadAllText(filePath);
else
return null;
// Find the place where "</Tags>" is located
int tagEnd = fileContents.IndexOf("</Tags>");
// Get the tags
string tagString = fileContents.Substring(6, tagEnd - 6).Replace(Environment.NewLine, ""); // 6 comes from the length of "<Tags>"
return tagString.Split(',').ToList();
}
Then to get the text you'd need this:
public string GetText(string filePath)
{
string fileContents;
// read the file if it exists
if (File.Exists(filePath))
fileContents = File.ReadAllText(filePath);
else
return null;
// Find the place where the text content begins
int textStart = fileContents.IndexOf("<Text>") + 6 + Environment.NewLine.Length; // The length on newLine is neccecary because the line shift after "<Text>" shall NOT be included in the text content
// Find the place where the text content ends
int textEnd = fileContents.LastIndexOf("</Text>");
return fileContents.Substring(textStart, textEnd - textStart - Environment.NewLine.Length); // The length again to NOT include a line shift added earlier by code
}
Then I'll let you find out how you do the rest.
The second way
In this solution you have a database file over all your files and their associated tags. This database file would look like this:
[filename]:[tags]
file.txt:tag1, tag2, tag3
file2.txt:tag4, tag5, tag6
The program will then read the file name and the tags in this way:
public static void LoadDatabase(string databasePath)
{
string[] fileContents;
// End process if database doesn't exist
if (File.Exists(databasePath))
return;
fileContents = File.ReadAllLines(databasePath); // Read all lines seperately and put them into an array
foreach (string str in fileContents)
{
string fileName = str.Split(':')[0]; // Get the filename
string tags = str.Split(':')[1]; // Get the tags
// Do what you must with the information
}
}
I hope this helps.
I'm writing a program about trying different images in picturebox, but the image must correspond to the text. Plus it must come from "Resources" folder of the project.
this is what i want to do if the text "apple" displays to the screen then the image with a filename "apple" would also display in the picturebox..
I can do it in "if-else" like this
string word="apple";
if(word==apple)
pictureBox1.Image= WindowsFormsApplication4.Properties.Resources.apple;
but What if I have a thousand images, I still think there's an easy way for this,..
i'm trying this one,,
string word=label1.Text;//label1.text changes from time to time
pictureBox1.Image= WindowsFormsApplication4.Properties.Resources.word;
but I know "word" is string....It's not possible...I cannot append string to the syntax....
You can pass in a string using the GetObject method of the ResourceManager class:
string itemName = label1.Text;
this.pictureBox1.Image =
(Image)Properties.Resources.ResourceManager.GetObject(itemName);
If you open resources .Designer.cs file code , you will see something like:
internal static System.Drawing.Bitmap apple {
get {
object obj = ResourceManager.GetObject("apple", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
so you can do the same thing:
string word=label1.Text;//label1.text changes from time to time
pictureBox1.Image= (System.Drawing.Bitmap)WindowsFormsApplication4
.Properties
.Resources
.ResourceManager.GetObject(word);