I have added functionality to speak with NPCs and I wanted the text to be animated like the typewriter animation in PowerPoint (The text appears letter by letter). I have been able to do so but sometimes the text dissappears for a frame and then reappears.
The entire class is very long so I have included the relavent function. I achieve the animated effect by creating a substring of the original text which increases in length with time so that more of the text is displayed.
void DisplaySpeech() {
GUI.BeginGroup(new Rect(Screen.width*0.05f, Screen.height*0.7f, Screen.width*0.9f, Screen.height*0.25f));
GUI.Box(new Rect(0,0,Screen.width*0.9f, Screen.height*0.25f),""); //Draws background for text
GUILayout.Label("Text", titleGuiStyle); //A placeholder title will modify later
string sub = interactions.interactions[interactionSelector].text[textSelector].Substring(0,Mathf.RoundToInt(charSelector));
//The interactions.interactions[interactionSelector].text[textSelector] variable contains a list of strings which are displayed on after another
//To achieve an animated effect the string is cut into a substring which starts at the beginning for a set number of characters which increase over time
//The string is then applied to a Label
GUILayout.Label(sub);
GUI.EndGroup();
charSelector += Time.deltaTime*textSpeed; //This variable increases with time and so allows for more the string to be copied to the Substring
if(charSelector >= interactions.interactions[interactionSelector].text[textSelector].Length) { //If the charSelector becomes too large for the string
charSelector = interactions.interactions[interactionSelector].text[textSelector].Length; //Set charSelector to the size of the string
GUI.Label(new Rect(0,0,Screen.width*0.9f, Screen.height*0.25f), "Continue", titleGuiStyle); //Tells the player that the text has been displayed
if(Input.GetButtonDown("Interact")) { //If the player continues
textSelector++; //Increasing the textSelector allows for the next string to be displayed
charSelector = 1; //Resets the charSelector
}
if(textSelector >= interactions.interactions[interactionSelector].text.Count) { //If the textSelector is greater than the number of strings
Reset(); //Reset all relevant values to this function
currentMode = modes.SETFLAGS; //Sets flags relavent to this interaction
}
}
}
To help people understand the interactions variable is a ScriptableObject containing data about NPCs.
It also contains possible dialogues, interactions.interactions[interactionSelector].text is a list of strings for a dialogue.
↧