Reputation: 19
So, I have some text that shows up when there is no grenades and currently, it disappears after 2 seconds and then it flickers forever. I just want it to appear for 2 seconds and disappear. Would appreciate some help!
if (amountOfGrenades == 0)
{
StartCoroutine(ShowandHideGrenadeText(NOgrenadesText));
}
IEnumerator ShowandHideGrenadeText(GameObject NOgrenadesText)
{
NOgrenadesText.SetActive(true); // Enable the text so it shows
yield return new WaitForSeconds(2.0f);
NOgrenadesText.SetActive(false); // Disable the text so it is hidden
yield return new WaitForSeconds(2.0f);
}
Upvotes: 0
Views: 311
Reputation: 90749
Since there is not much context provided My guess: you are starting hundreds of parallel coroutines because your first snippet is called within Update every frame while the condition is met ...
Simply add a second condition like e.g.
if (amountOfGrenades == 0 && !NOgrenadesText.activeSelf)
{
StartCoroutine(ShowObjectForTwoSeconds(NOgrenadesText));
}
// In general be careful with paramter names and existing fields with the same name
// you might confuse them at some point
IEnumerator ShowObjectForTwoSeconds(GameObject obj)
{
obj.SetActive(true); // Enable the text so it shows
yield return new WaitForSeconds(2.0f);
obj.SetActive(false); // Disable the text so it is hidden
}
Note that a yield
at the end of a Coroutine makes little sense ;)
Or if you really want to wait also 2 secs after turning it back off before being able to.tirn it on again then just introduce an additional flag like e.g.
if (amountOfGrenades == 0 && ! alreadyShowing
{
StartCoroutine(ShowObjectForTwoSeconds(NOgrenadesText));
}
private bool alreadyShowing;
// In general be careful with paramter names and existing fields with the same name
// you might confuse them at some point
IEnumerator ShowObjectForTwoSeconds(GameObject obj)
{
alreadyShowing = true;
obj.SetActive(true); // Enable the text so it shows
yield return new WaitForSeconds(2.0f);
obj.SetActive(false); // Disable the text so it is hidden
yield return new WaitForSeconds(2.0f);
alreadyShowing = false;
}
Upvotes: 1
Reputation: 4037
Just to give you another possibility to handle this:
Have you thought about using an animation for these kinds of things? And by animation, I mean "not a coroutine."
There are multiple ways to animate this. You could use an AnimationCurve
and set the color of the text based on said curve. Or you could create an animation and have an animator for that part of the UI. In the code, you would just trigger a state change in the animator.
Coroutines can be used for the effect you want, but they also come with problems.
This may not be a direct answer to your question, but a solution for a possible xy-problem that you currently have.
Upvotes: 0