- Home /
Other
How do I keep an increment process continuous without the update function?
void gravincrease()
{
Physics.gravity = grav;
grav.y -= 0.05f * Time.deltaTime;
}
I don't want to write this code in update. Because whenever I want, I want to using CancelInvoke. How can I make such a function permanent? or how can I stop these codes for a while when I start a coroutine?
IEnumerator downgrav()
{
Vector3 initialGravity = Physics.gravity;
Physics.gravity = initialGravity * 0.5f;
stopgrav = true;
yield return new WaitForSeconds(10f);
Physics.gravity = initialGravity;
stopgrav = false;
}
{
if (stopgrav==true)
{
CancelInvoke("gravincrease");
}
}
Actually what I want to do is to make this part work.
It is important to show in what function your code is. And also the code that calls your functions. Who runs gravincrease()? Is it in an InvokeRepeating() call? If you call CancelInvoke() it will stop all Invokes and you have to start them again when you want that. Personally I want to write all my code in Update, and never use Coroutines or Invokes.
Answer by UnityToMakeMoney · Oct 01, 2020 at 10:19 PM
I would just make a WaitForSeconds coroutine with no delay and stop the coroutine through a boolean flag.
IEnumerator gravincrease(float delay=0f){//default argument - does not need to be filled
yield return new WaitForSeconds(delay);//wait for delay
Physics.gravity = grav;
grav.y -= 0.05f;
if(!boolFlag)//if your flag is false
StartCoroutine(gravincrease(delay));//call this function again
}
Hoped this helped :). Also as a side note, it is recommended to comment your code and camelcase (or some other method) to name functions and variables.
bool stopcor=false;
public void gravdown()
{
StartCoroutine(downgrav());
}
IEnumerator downgrav()
{
stopcor = true;
Vector3 initialGravity = Physics.gravity;
Physics.gravity = initialGravity * 0.5f;
yield return new WaitForSeconds(10f);
Physics.gravity = initialGravity;
stopcor = false;
}
void Update()
{
if (stopcor == false)
{
if(grav.y>-11)
grav.y -= 0.05f * Time.deltaTime;
Physics.gravity = grav;
}
}
Thanks a lot for the help. I solved the problem by trying. I also used bool but in a different way.
Answer by Zaeran · Oct 01, 2020 at 05:10 PM
You can assign a coroutine to a variable like so:
Coroutine downGravCoroutine = StartCoroutine(downgrav());
You can then stop it later using:
StopCoroutine(downGravCoroutine());
I guess these codes are so that I can stop the "downgrav" part. The process I want to pause for a while is an increase in gravity over time.
Follow this Question
Related Questions
Any way to stop a build? 3 Answers
Stop instance 1 Answer
Cancel WWW post operation 1 Answer
Walking Animation 1 Answer
Unity exported application stops when its not on focus, how can I disable this? 1 Answer