- Home /
Problems with txt reading
Hello everyone, I'm a beginner programmer making a rhythm game. The gameplay works fine, but now it's time to put the notes in the correct order for creating a melody.
As placing the notes on the screen one by one is a pain in the neck(as I would have to place hundreds of notes and manually set them to match the song tempo), I figured out how to "record" songs, in order to later access that recording and make the game play the notes.
What I did is to play the notes as if I was actually playing the game and then I save in a txt file what note I pressed and when it was pressed. The format is = "whenitwasplayed / whatnoteisit"
And what I wanna do is to compare the time when playing the game with the time recorded to instantiate notes in the exact time... but I don't know how to do it... I've searched in some other forums and questions but nothing seems to work for me
Can somebody help me?
Answer by SamElTerrible · Oct 14, 2021 at 03:31 PM
If I understand correctly, would it be something like:
If the first note to instantiate appears 5 seconds into the game, then you want to know when the player has been playing for 5 seconds.
If that's the case, I'd imagine you have something like a start button. So what you would do is record Time.time
at that point and save it as a float or double (e.g. double gameStartTime = Time.time;
Then on your Update method, you can check if 5 seconds have passed by doing:
if(Time.time - gameStartTime >= 5)
{
//Show a note
}
Obviously you'd want to do something more dynamic than hardcoding all the note instantiation times, but this should get you started
Thank you very much, but I already knew that. What I wanted to knew was how do I convert the text I have saved in txt to a readable float for unity and then comparing this floats with the method you said.
The txt is just a list of floats, one per line. And what I want is that for each number that coincides (one number of the txt with the time of the game since it started), instantiate a note.
Oh my bad!
In that case you can use a JSON instead of a normal .txt file.
You can create a struct like this:
public struct Note
{
public float Note;
public float TimePlayed;
}
and your JSON can contain an array of Notes. You can then deserialize your JSON into an array of Notes. From there, you will be able to access all the Notes from your JSON file and use them whichever way you need.
Just a side note, I think your object needs to have the attribute [System.Serializable]
above its definition (I may be wrong).
Then, check out Json Utility for the actual json serialization stuff.
Finally, for my rhythm game, I saved the time since the last note instead of the TimePlayed. That way, I can use a coroutine to wait that time and spawn the note, for each note.
Your answer
Follow this Question
Related Questions
How to display *.txt file on the cube model? 2 Answers
Highscores in text file 0 Answers
Read txt file from Android Downloads file 1 Answer