Empty array if strings in c# for unity game - c#

I am trying to empty and array of strings every-time a user clicks on load profiles so that the array doesn't get over populated with the same profiles over and over again every time they click load.
This is my array:
string[] files;
This is how i get the profiles but i need to empty it whenever getProfiles is called so it doesn't over populate with duplicate profiles
private void GetProfiles()
{
//Check if directory with saved profiles exists
if (Directory.Exists(filePath))
{
//Clear files array
//Get all of the file paths of each file in this directory
files = Directory.GetFiles(filePath);
//profileTileTemplate.SetActive(true);
//Go through each file and read the data and create a profile for each json file
for(int i = 1; i <= files.Length -1; i++)
{
string json = File.ReadAllText(files[i]);
Profile savedProfile = JsonUtility.FromJson<Profile>(json);
Instantiate(profileTileTemplate,LoadProfileTransform);
profileTileTemplate.SetActive(true);
profileTileTemplate.GetComponentInChildren<Text>().text = savedProfile.playerName;
Debug.Log(savedProfile.playerName);
}
}
}
how do i clear this array?
I have tried setting it to null but it doesn't work.

Question is not clear, but if you want to empty the array and stay with the same length then you can write this wherever you want to.
files = new string[files.Length];

As said I don't think this is related to the array at all .. GetFiles everytime returns a new array there are no duplicates.
However, you Instantiate a bunch of objects into the scene and never destroy them!
You could do this first
foreach(Transform child in LoadProfileTransform)
{
Destroy (child.gameObject);
}
and then you could simply do
foreach(var path in files)
{
var json = File.ReadAllText(path);
var savedProfile = JsonUtility.FromJson<Profile>(json);
var obj = Instantiate(profileTileTemplate,LoadProfileTransform);
obj.SetActive(true);
obj.GetComponentInChildren<Text>().text = savedProfile.playerName;
Debug.Log(savedProfile.playerName);
}
since you want to apply the text etc to the newly instantiated objects, not the original prefab.

Related

Select Random line from Text File and display on unity

I was creating a form which contains contact details on unity for a game. I managed to connect text file with unity and write lines to it but I am not sure how to get a random person from text file and display it on unity. If someone has any idea about this please help me out..
If you link your file via e.g
public TextAsset file;
then you could e.g. do
private string GetRandomLine()
{
var lines = file.text.Split('/n');
var randomIndex = Random.Range(0, lines.Length);
return lines[randomIndex];
}
Or if you use system FileIo you can do
var lines = File.ReadAllLines(path);
var randomIndex = Random.Range(0, lines.Length);
return lines[randomIndex];
Of course you might want to cache the file content and lines somewhere etc but I hope the idea gets clear.

Importing each line from text file from Resources in Unity to list in C#

I have a text file in my Assets/Resources/Text, on Start() I want to import each line from the text file as a string in list. Using this code does it for me,
string[] AllWords = File.ReadAllLines(#"C:\Users\jamal\Downloads\English\english-words-master\New folder\AllWords.txt");
listOfWords = new List<string>(AllWords);
But how do I do the same when the file is in my Resources folder, I can't seem to use File.ReadAllLines.
Any help would be of great help, thank you!
The text file contains all the words in a dictionary, here's how the text file goes:
aahed
aahing
aahs
aal
aalii
aaliis
aals
aam
aani
aardvark
aardvarks
aardwolf
aardwolves
aargh
aaron
aaronic
aaronical
aaronite
aaronitic
To begin with Don't use Reources!
If against Unity's own recommendation you still want to do it for some reason then you have to load that resource using Resources.Load in your case as a TextAsset like e.g.
// assuming your path is e.g. "Assets/Resources/Text/AllWords.txt"
var file = Resources.Load<TextAsset>("Text/AllWords");
var content = file.text;
var AllWords = content.Split("\n");
listOfWords = new List<string>(AllWords);
The better approach though would probably be to listen to what Unity recommends and instead of using Resources at all rather place your file into the Assets/StreamingAssets folder and access it later via Application.streamingAssetsPath
either using as you did
string[] AllWords = File.ReadAllLines(Path.Combine(Application.streamingAssetsPath, "AllWords.txt");
listOfWords = new List<string>(AllWords);
Or - depending on the platform, e.g. in Android you can't directly access the StreamingAssets
StartCoroutine(LoadWords());
...
private IEnumerator GetRequest()
{
var url = Path.Combine(Application.streamingAssetsPath, "AllWords.txt");
using (var webRequest = UnityWebRequest.Get(url))
{
// Request and wait for result
yield return webRequest.SendWebRequest();
switch (webRequest.result)
{
case UnityWebRequest.Result.Success:
var content = webRequest.downloadHandler.text;
var AllWords = content.Split("\n");
listOfWords = new List<string>(AllWords);
break;
default:
Debug.LogError($"Failed loading file \"{url}\" - {webRequest.error}", this);
break;
}
}
}
You could actually also simply put your file into a "normal" folder like Assets/AllWords.txt and then directly reference it via the Inspector in a
public TextAsset file;
or
[SerializeField] private TextAsset file;
and then access the content via
var content = file.text;
var AllWords = content.Split("\n");
listOfWords = new List<string>(AllWords);

Get Music files details only

Basically I am trying to get the details of a music file inside an android device (Ex. The music's title, artist, etc) and store them to a list<>. (SongData contains the list, and it contains a list of Song object.)
public void PopulateSongList(Context context) {
SongData songData = new SongData();
Android.Net.Uri musicUri = Android.Provider.MediaStore.Audio.Media.ExternalContentUri;
//Used to query the media files.
ICursor musicCursor = context.ContentResolver.Query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.MoveToFirst())
{
int songID = 0;
//get columns.
int songTitleColumn = musicCursor.GetColumnIndex("title");
int songArtistColumn = musicCursor.GetColumnIndex("artist");
//add songs to list
do
{
String songTitle = musicCursor.GetString(songTitleColumn);
//Tried, but file name does not contain file extension.
if (songTitle.ToLower().Contains(".mp4") || songTitle.ToLower().Contains(".m4a"))
{
String songArtist = musicCursor.GetString(songArtistColumn);
songData.AddNewSong(new Song(++songID, songTitle, songArtist, null));
}
}
while (musicCursor.MoveToNext());
}
}
The code works well but however in the do..while loop, songTitle also contains other files that are not music files as well.
I tried checking for file extensions but it does not work, and after using the debugger again, the file name given does not contain the file extension.
So how do I make sure that it only grabs details from a music file, and not other kind of files?
(Also, I want to grab the name of the artist of a music file, but apparently int songArtistColumn = musicCursor.GetColumnIndex("artist"); does not seem to work.)
Finally, how do I get the image of a music file? (The song image).
You can try to use musicCursor.GetColumnNames() to see what the file is allowing you to work with.
Here's an image of the possible results you can get if you execute it.
musicCursor.GetColumnNames() will return the results in a string[] so you can use List<string> songInfo = new List<string>(string[]);
A problem you might get is a NullException, this happens when the data you're trying to work with have a value of null. You'll get this value directly from the file if the Artist or other values are unknown.
I don't know where the Image file is stored, but if it's stored with the music file it will most likely be stored in a byte[]. So you'll need to convert the byte[] to an image.

iTextSharp Parsing PDF Objects with a view to removing those not in use

As per question Remove unused image objects
I was told I'd effectively have to parse a PDF file, take note of the global object names, then remove those not in use.
I would not have even an inkling of where to start.
I was having a look in VS2010 local viewer and I could see in a page there was an array called Matrix. This seems to contain the XObjects in use in the page. But Matrix does not seem to be a property that the API allows.
I also found in my reader an xrefObj array, which seems to be every object. WHen looking at the XObjects i found a number of PRStream objects which corresponded in size to teh actual images.
iTextSharp.text.pdf.PdfDictionary dictionary = reader.GetPageN(i);
iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, i);
iTextSharp.text.pdf.PdfDictionary res = (iTextSharp.text.pdf.PdfDictionary)iTextSharp.text.pdf.PdfReader.GetPdfObject(dictionary.Get(iTextSharp.text.pdf.PdfName.RESOURCES));
iTextSharp.text.pdf.PdfDictionary xobj = (iTextSharp.text.pdf.PdfDictionary)iTextSharp.text.pdf.PdfReader.GetPdfObject(res.Get(iTextSharp.text.pdf.PdfName.XOBJECT));
foreach (iTextSharp.text.pdf.PdfName name in xobj.Keys)
{
iTextSharp.text.pdf.PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
iTextSharp.text.pdf.PdfDictionary tg = (iTextSharp.text.pdf.PdfDictionary)iTextSharp.text.pdf.PdfReader.GetPdfObject(obj);
iTextSharp.text.pdf.PdfName type = (iTextSharp.text.pdf.PdfName)iTextSharp.text.pdf.PdfReader.GetPdfObject(tg.Get(iTextSharp.text.pdf.PdfName.SUBTYPE));
if (iTextSharp.text.pdf.PdfName.IMAGE.Equals(type))
{
int XrefIndex = Convert.ToInt32(((iTextSharp.text.pdf.PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
iTextSharp.text.pdf.PdfObject pdfObj = reader.GetPdfObject(XrefIndex);
iTextSharp.text.pdf.PdfStream pdfStream = (iTextSharp.text.pdf.PdfStream)pdfObj;
}
}
}
This block, seems to give me the entire catalog of resources - as opposed to the specific used ones on the page.
So I guess what I'm asking for is:
-How can I match what is actually in my PDF file (I assume I make a list of all the ObjNum) references on each actual page of my File against the master list that is held in the reader.
-Remove all references that are not kept in my references list and save in place (this is a temporary file so in place would be fine.
Thanks in advance.
So to identify the images on the page, I used a PdfReaderContentParser.
iTextSharp.text.pdf.parser.PdfReaderContentParser parser = new iTextSharp.text.pdf.parser.PdfReaderContentParser(reader);
MyImageRenderListener listener = new MyImageRenderListener();
while (i < numberofPages)
{
i++;
parser.ProcessContent(i, listener);
}
The MyImageRenderListener is a new class inheriting: iTextSharp.text.pdf.parser.IRenderListener
All I did was add all the names to a list that's accessible from the original class:"
public void RenderImage(iTextSharp.text.pdf.parser.ImageRenderInfo renderInfo)
{
iTextSharp.text.pdf.parser.PdfImageObject image = renderInfo.GetImage();
if (image == null) return;
ImageNames.Add(renderInfo.GetRef().Number);
}
The I used the code posted in the original question as the basis of the master image list.

C# Using Lists to read, write and search text file lines

I need to perform the following operations with a text file and a List:
Read all lines of text file (non delimited) into a string based list
Whilst the application is open I need to do the following:
Check for instances of a string in the List
Add new entries to the List
Remove all identical instances of a defined string from the List
Write the contents of the List back to the text file including any changes made as soon as they are made
Firstly, how do I read and write between Lists and text files?
Secondly, how do I search a List for a string?
Lastly, how do I safely remove an item out of a List without leaving gaps in the text file I write?
public void homework()
{
string filePath = #"E:\test.txt";
string stringToAdd = "test_new";
IList readLines = new List();
// Read the file line-wise into List
using(var streamReader = new StreamReader(filePath, Encoding.Default))
{
while(!streamReader.EndOfStream)
{
readLines.Add(streamReader.ReadLine());
}
}
// If list contains stringToAdd then remove all its instances from the list; otherwise add stringToAdd to the list
if (readLines.Contains(stringToAdd))
{
readLines.Remove(stringToAdd);
}
else
{
readLines.Add(stringToAdd);
}
// Write the modified list to the file
using (var streamWriter = new StreamWriter(filePath, false, Encoding.Default))
{
foreach(string line in readLines)
{
streamWriter.WriteLine(line);
}
}
}
Try to google before you post the question.
I'd start here:
Read from text file: http://dotnetperls.com/readline
List Actions
1. Removing from a list
2. Searching in a List
Write to a text file: http://www.csharp-station.com/HowTo/ReadWriteTextFile.aspx
I'll just share my idea...
using System.IO;
public void newMethod()
{
//get path of the textfile
string textToEdit = #"D:\textfile.txt";
//read all lines of text
List<string> allLines = File.ReadAllLines(textToEdit).ToList();
//from Devendra's answer
if (allLines.Contains(stringToAdd))
{
allLines.Remove(stringToAdd);
}
else
{
allLines.Add(stringToAdd);
}
//extra: get index and edit
int i = allLines.FindIndex(stringToEdit => stringToEdit.Contains("need to edit")) ;
allLines[i] = "edit";
//save all lines
File.WriteAllLines(textToEdit, allLines.ToArray());
}

Categories

Resources