How to display text with delay (No GUI code in script)
Hi !
I am really new to coding in Unity, and I'm trying to make a text appear after 3 seconds, but the GUI Text Box is in my Unity 2D scene and not in the script. Here is my Code, It's actually way bigger than this but this is basically what you guys should need to help me. Thanks !
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour {
public AudioClip cenasound;
public Text text;
private enum States
{forest,forest_v, bushes_0, treetrunk_0, birdnest_0, snail, snail_v,
birdnest_1, bushes_1, treetrunk_1,
lightbulb_1, lightbulb_0,
cabinfound_1, cabinfound_0,
inCabin_bulb, inCabin_nobulb,};
private States myState;
// Use this for initialization
void Start () {
myState = States.forest;
}
void Update () {
if (myState == States.cabinfound_0) {cabinfound_0();}
}
void cabinfound_0 () {
text.text = "blahblah";
}
void lightbulb_0() {
text.text = "\n\n\t\t\t\t\t\tThis action will have consequences...\n\n\n Press the spacebar to continue.";
if (Input.GetKeyDown(KeyCode.Space)) {myState = States.cabinfound_0;}
}
Answer by Cepheid · Nov 07, 2015 at 09:49 PM
Hi there! @MrWhiteSwitch I assume you're using the new 4.6 Unity GUI? If so then there are a couple of quick ways of doing this by simply using the Invoke method. (If I've understood the question correctly).
The first will require a GameObject reference for your text component which we can then activate and deactivate as shown below:
public GameObject textBox;
void Start ()
{
textBox.SetActive(false);
Invoke(DisplayText, 3f);
}
void DisplayText ()
{
textBox.SetActive(true);
}
However if all that you have on screen is a text box and no background image as child. Then the other way of doing this would be to simply start the text with an empty string value and then simply assign the string you wish it to display after 3 seconds like so:
void Start ()
{
text.text = "";
Invoke(DisplayText, 3f);
}
void DisplayText ()
{
text.text = "I am now display text.";
}
Now I'm sure you don't want to the delay to begin in Start but you can place the Invoke method wherever you want and it will wait for 3 or however many seconds you want it to before executing the DisplayText method. I hope this helps! If I've completely misunderstood you though and given you a pointless answer please feel free to correct me so that I can possibly give you a more suited answer.
Your answer
