- Home /
Problems in the script for making a text disappear after few seconds
Hi there! I am currently developing a simple game. Basically, it consists in touching a series of boxes through a sphere. Every time a box is being touched it changes color and the player gets 1 point more. I am trying to add a message (that pops up just for few second and then disappears) every time the sphere touches a box. For now, I write something that works just the for the first collision between the sphere and the box, but, unfortunately, when the sphere touches the following box the game works no more. Does anybody know how to help me?
Here is the code that I write and I attached to the sphere:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Message: MonoBehaviour {
public Text tex;
float time = 2f;
void Start()
{
tex.gameObject.SetActive(false);
}
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.tag == "coloredbox")
{
tex.gameObject.SetActive(true);
Invoke("Hide", time);
}
}
void Hide()
{
Destroy(tex);
}
}
Answer by Artik2442 · Jun 09, 2020 at 09:08 AM
You are destroying your text in your Hide method. So, in game, you won't be able to use the text a second time because it no longer exist! So, I think that you can replace Destroy(tex);
by tex.gameObject.SetActive(false)
.
Answer by WinterboltGames · Jun 09, 2020 at 09:10 AM
using System.Collections;
using UnityEngine;
public class Message : MonoBehaviour
{
[SerializeField] private Text _text;
[SerializeField] private float _time;
private void Start()
{
_text.enabled = false;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("coloredBox"))
{
StartCoroutine(ShowMessage());
}
}
private IEnumerator ShowMessage()
{
_text.enabled = true;
yield return new WaitForSeconds(_time);
_text.enabled = false;
}
}