Reputation:
i am looking to execute a specific piece of code directly after the first one has finished and not at the same time like they are currently running.
private void Update()
{
//This is the code to be executed first
if ((textActive == true) && (stopText == false))
{
Debug.Log("TextActive");
KeyText("On");
objectToEnable4.SetActive(true);
stopText = true;
}
//after which this code will execute to disable Object4
if (stopText == true)
{
objectToEnable4.SetActive(false);
}
}
both pieces of code work perfectly i just need to implement a delay for the second code section i'm looking to delay the code for 2 seconds to allow time for an animation to play
thanks for the help in advance.
Upvotes: 0
Views: 1376
Reputation: 1
imo there's an even 'better' way (at least, simpler way) using Invoke.
private void Update()
{
if (textActive && !stopText)
{
KeyText("On");
objectToEnable4.SetActive(true);
stopText = true;
Invoke("MyDelay", 2);
}
}
private void MyDelay()
{
if (stopText)
{
objectToEnable4.SetActive(false);
}
}
I'm not sure why you even need to use the bool stopText, maybe for something else you haven't shown us? If not you could remove that too!
Upvotes: 0
Reputation: 1
Base on the code that you have provided, I think they are doing just what you want it to do: Execute in order. However, because the code is very simple so it may seems like they are running at the same time, which make you can not see the objectToEnable4 at all. The way you can pause the execution is by using Unity's Coroutine.
The following code are the example of coroutine at Unity's Scritping API:
using UnityEngine;
using System.Collections;
public class WaitForSecondsExample : MonoBehaviour
{
void Start()
{
StartCoroutine(Example());
}
IEnumerator Example()
{
print(Time.time);
yield return new WaitForSecondsRealtime(5);
print(Time.time);
}
}
The first answer perfectly applied the corotine to your code. Hope you find it useful.
Upvotes: 0
Reputation: 4343
Good time to use a coroutine:
private void Update()
{
//This is the code to be executed first
if ((textActive == true) && (stopText == false))
{
Debug.Log("TextActive");
KeyText("On");
objectToEnable4.SetActive(true);
stopText = true;
StartCoroutine(myDelay());
}
}
IEnumerator myDelay()
{
// waits for two seconds before continuing
yield return new WaitForSeconds(2f);
if (stopText == true)
{
objectToEnable4.SetActive(false);
}
}
Upvotes: 1