Method Skipping Inputs
I'm using a method to run an if statement after each line of text has been read by the user. Pressing Tab will change the line of text to the next:
public void NextText(string nextLine) {
if (Input.GetKeyDown (KeyCode.Tab))
{
text.text = nextLine;
}
I'm calling it in another method:
void Update () {
NextText("Line 1");
NextText("Line 2");
}
Unfortunately, though, if I were to run the script and press Tab for the first time, it will play Line 2 instead of Line 1.
I'm about as beginner as it gets but learning. I appreciate your patience.
Answer by ElijahShadbolt · Dec 18, 2016 at 09:18 AM
This is what your script is doing right now: every single frame, Unity calls the function Update(). This means that in each frame, it first calls NextText("Line 1"), then NextText("Line 2"). If you have just pressed tab during this frame, it first changes the text to "Line 1", and then immediately changes it to "Line 2" in the same frame.
I think you could do this
int currentMessage = 0;
void Update() {
if (currentMessage == 0)
NextText("Line 1");
else if (currentMessage == 1)
NextText("Line 2");
}
public void NextText(string nextLine) {
if (Input.GetKeyDown(KeyCode.Tab))
{
text.text = nextLine; // set text to current message
currentMessage++; // add 1 to currentMessage
}
}
Or better yet, use an array (and you can change each item in the inspector)
// initialize an array with two items
public string[] messages = new string[] {
"Line 1",
"Line 2"
};
public int currentMessage = 0; // the index in the array
void Update() {
// if index is out of range, do not try
// to get messages[currentMessage] since it doesn't exist
if (currentMessage < messages.Length)
NextText(messages[currentMessage]);
}
public void NextText(string nextLine) {
if (Input.GetKeyDown(KeyCode.Tab))
{
text.text = nextLine; // set text to current message
currentMessage++; // add 1 to currentMessage
}
}
Answer by god_damniel · Dec 20, 2016 at 02:51 AM
You're a genius, and I greatly appreciate your input.
Your answer
Follow this Question
Related Questions
Link UI Input field to Google Map Script 1 Answer
Dynamic Menu C# 0 Answers
CrossPlatformInput Detect Multiple Input Headache 1 Answer
Detecting if is currently entering text on any component. 0 Answers