Make text disappear after a few seconds.

Hello guys!

I have a bush with this code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class talkToUI : MonoBehaviour {

	public Text propToUI;
	public string message;

//	Display message from public variable to UI text label on mouse click...
	void OnMouseDown()
	{
		propToUI.text = message;
	}
}

when I click the bush, the text I enter on the public message variable appears. Until here all is fine…

Now I would like the text to disapear after 3 seconds and I can’t figure out how to do it! It has been a few hours now and I need your help!

Could you please put me in the right direction?

Thanks!

Julian

Well the easiest way I can think of is using Destroy();. This ‘function’ will remove whatever game object you tell it to. However it is permanent. If you are looking for temporary removal you could disable the text and enable it again later. Alternatively, if you are looking for something temporary, you could have propToUI.text = “” after a certain amount of time.

I hope this helped. If it didn’t feel free to give more information and I’ll see what I can think up :slight_smile:

Destroy:

//Destroy takes 2 variables, the gameobject and time (in seconds)
Destroy(YourGameObject, AmountOfTime);

Hey thanks @fiterpilot !!

There are interesting ideas!

How would you tell unity to wait a few seconds before having propToUI.text = “” after a certain amount of time then?

And…

Would you recommend animating the opacity of the UI text label so it is opaque for a few second and then fade out?

Hello!
I have the same problem.

I want to a “Miss!” text when my player misses an enemy… and after a few seconds (2 seconds) that “Miss!” string should disappear.

I tried with IEnumerators … wait for seconds and then write again myText.text =“”;
it won’t work … that “Miss!” text is shown forever.

The only think that work is “Destroy (myText,2)”. But … doing this other “Miss!” won’t be displayed!

How is the right way to keep a text on screen for a few seconds and then make it disappear but … Not forever! If a method will ask for “myText” again … it must work!

Thanks!

@Complexium you could use the following to fade the text:
propToUI.CrossFadeAlpha(target alpha. time duration the text should fade in, false);
and then afterwards use:

propToUI.enabled = false;

In some cases the code above might not work so you can use:

propToUI.gameObject.SetActive = false;

To tell unity to wait for a few seconds you will have to use coroutines and IEnumerators. Unity - Scripting API: Coroutine