- Home /
How do I reveal a text for a moment before making it disappear?
The player is supposed to pick up a note (represented by a square block here) and a message appears telling the player that their "journal" has been updated. The text should not destroy itself as technically it needs to appear multiple times whenever the player picks up a "note". I managed to simulate this by having the square block destroy itself upon click and change a Boolean to true to get the text to reveal itself. However, I can't get the text reveal to appear long enough to notify the player that their "journal" has been updated. I tried to use a for loop which obviously failed and I searched up online and found out about IEnumerator and things like that but I don't know how to implement them. How do I do this text reveal thing? (I'm using Unity 2019.2.17f1)
public void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
Destroy(gameObject);
Debug.Log("Pressed");
NotePickedUp = true;
Debug.Log("Note has been picked up");
}
if (NotePickedUp == true)
{
for (int i = 0; i < 3; i++)
{
canvas.transform.GetChild(0).gameObject.SetActive(true);
Debug.Log("Counting...");
}
canvas.transform.GetChild(0).gameObject.SetActive(false);
}
}
Answer by utzsar · Feb 16, 2020 at 02:17 PM
here's how you would implement the IEnumerator for this, which would be the easiest method here if you want it to just pop up for a set amount of time and then go away.
IEnumerator ShowNoteText()
{
canvas.transform.GetChild(0).gameObject.SetActive(true);
yield return new WaitForSeconds(3); // set for however long you want it open.
canvas.transform.GetChild(0).gameObject.SetActive(false);
}
then when the note is picked up on your mouseclick function, put this
StartCoroutine(ShowNoteText());
you wont even need the notepickedup=true bool, unless you're using that for something else too.
fyi, the reason your for loop isn't working for this is because it iterates too fast. that function would have counted through three items in fractions of a second. for loops like that are for iterating through groups of items quickly, not counting time. to do that you would have to save the current Time.time as a float and compare it to another captured Time.time, but that's prolly way more complex than what you need in this instance. IEnumerators are perfect for this kinda thing :D