Hello. Im very new to Unity and c# aswell, so my answer is probably gonna be very dull !
Basically I have a text displayed on the screen and I’d like for a dot to appear and disappear constantly at the end of the text every 1 second.
I create a Ienumerator like this
IEnumerator Wait2()
{
// Add the dot at the end of the text
text.text = (text.text + ".");
Debug.Log("Added dot");
// Wait 1 Second
yield return new WaitForSeconds(1f * Time.deltaTime);
// remove the dot
text.text = text.text.Remove(text.text.Length - 1);
Debug.Log("Removed dot");
But as a result I can see in the Debug Log that the dot gets added and deleted at the same time, without waiting the 1 second. I’ve been stuck on this for one day, please help me before I loose my mind.
When using WaitForSeconds(time), you don’t have to multiply by Time.deltaTime since it’s just going to wait for whatever time you pass in. Multiplying by Time.deltaTime basically made your Coroutine wait for almost 0 seconds every time before continuing.
After implementing what @gjf said, you will need a mechanism to have the coroutine keep repeating itself (if that is what you intended it to do). You can accomplish this by calling StartCoroutine on the coroutine itself at the end of the routine.
See my code below for a complete solution based off these three points.
Here is my code suggestion:
void Start()
{
StartCoroutine(Wait2());
}
IEnumerator Wait2()
{
// Add the dot at the end of the text
text.text = (text.text + ".");
Debug.Log("Added dot");
// Wait 1 Second
yield return new WaitForSeconds(1f);
// remove the dot
text.text = text.text.Remove(text.text.Length - 1);
Debug.Log("Removed dot");
// Wait another 1 Second
yield return new WaitForSeconds(1f);
// Call the Coroutine to start again so it continuously loops
StartCoroutine(Wait2());
}
Update() is called every frame so starting a coroutine is a very bad idea… if you want to perform actions with wait periods, start it from Start()/Awake()