- Home /
Creating delays without delaying the script
Okay so I'm trying to make a puzzle game where the player is a wizard casting specific spells to get through specific levels. Some spells are supposed to kill you if you don't cast a second spell fast enough. For this I need a way to add a delay without stopping the rest of the script, as all the spells are on one script. I have tried creating a second script in which the function update is testing for specific static variables to be equal to an amount I set them to when specific spells are cast, however this has failed miserably. I would show some code but it is a horrible mess. Any advice?
What is a coroutine and how would I use it in this context?
Answer by TonicMind · May 12, 2016 at 03:36 AM
Just do something like this:
float time; //Counts up as time goes on public float timeThreshold; //Set this in the unity editor. It should be how long you want the spell to //"cool down" or in your case, how long before the player dies of not casting a spell.
bool KillPlayerNowFlag = false; //Check this bool when you need to know if its OK to kill the player for not casting a spell (should be true in that case).
void Update() { time += Time.deltaTime; //Counts upward every frame if(time > timeThreshold) { KillPlayerNowFlag = true; //OR: killPlayer(); time = 0f; //Reset to zero so the timer can be used again }
}
Answer by aditya · May 12, 2016 at 04:49 AM
void Start(){
invoke("afterDelay", 1f);
Debug.Log("Printing without any delay");
}
void afterDelay(){
Debug.Log("Printing with a delay of 1 second");
}
Use Invoke as this will give you a desired delay to invoke a specific method but will not delay your current method
Your answer
Follow this Question
Related Questions
Best way to emulate Swift String Interpolation in UnityScript? 1 Answer
UI Text showing weird string value? 1 Answer
"Script error: Update() can not be a coroutine.", please help 1 Answer
How do I get the scene to load in the background when on the loading screen? 2 Answers
Is this "scene switcher" script set up the right way? 1 Answer