- Home /
Set text to line in .txt file depending on player skill level
Hello UA! How exactly would I go about setting a text gameobject's text component to a line of text in a .txt file depending on the player level (Toejam and Earl for the genesis anyone?) I have a .txt file that goes along the lines of:
Level 1-3
Newbie
Level 4-7
Doofus
In pseudocode what I would do would be something like this:
if playerLevel > 0 && playerLevel < 3 {
text.Text = textfile.line1;
}
but how would this be accomplished in actual code? :p Thanks all.
EDIT- Thanks GameMaker_ , your latest comment solved the problem. 1 more question however, since it is a comment, how can I mark it at the correct answer?
You have to use the System.IO.StreamReader class like that:
StreamReader textFile = File.OpenText("FilePath"); // Load file
string line = textFile.ReadLine(); // Read the line and go to the next line
You can get more info about this class in the doc here.
Hi, thanks for replying. I cannot seem to figure this out however. I tried this: static StreamReader textFile = File.OpenText("Levels.txt");
public string line = textFile.ReadLine();
public Text text;
// Use this for initialization
void Start () {
text = GetComponent<Text>();
}
// Update is called once per frame
void Update () {
text = line;
}
But then Unity Editor throws me error CS0029: Cannot implicitly convert type 'string' to 'UnityEngine.UI.Text'
on line 21 (line 21 is the text = line;
code.) Any suggestions? :(
In your case you have a Unity UI Text component called "text". To set the value of that you need to access it like 'Text.text'. Hope this helps :)
Thanks, your latest comment solved my problem. 1 more question however, since it is a comment,do you know how can I mark it at the correct answer?
You're welcome ^^. To close the topic, click on the gear at the top right corner of your first post, and then click on "Close". And you can up vote a comment too: place a cursor over the comment, buttons will appear, and then click on "^" button.
Answer by sohail11330 · Aug 20, 2016 at 08:47 PM
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class example : MonoBehaviour {
public Text score;
// Use this for initialization
void Start () {
score.text = "TotalScore" ;
}
when you are trying to access the text then you should add a header file UnityEngine.UI;