# How can I stop this fixed update from executing

so I want this FixedUpdate() Method to stop executing when the Method OnMouseDown() is executed. A bool doesn't work a if() statement also doesn't work Please use my whole code Please help :) Thanks,

 private void FixedUpdate()
{
int random = Random.Range(1, 4);
if (random == 1)
{
m_SpriteRenderer = GetComponent<SpriteRenderer>();
m_SpriteRenderer.color = Color.green;
}
if (random == 2)
{
m_SpriteRenderer = GetComponent<SpriteRenderer>();
m_SpriteRenderer.color = Color.blue;
}
if (random == 3)
{
m_SpriteRenderer = GetComponent<SpriteRenderer>();
m_SpriteRenderer.color = Color.yellow;
}

}
private void OnMouseDown()
{
shouldexecute = false;
}

• Where do you actually try to use your shouldExecute bool? – DMGregory Oct 3 '19 at 20:06

From unity documentation: "FixedUpdate functions will not be called when timeScale is set to zero.".

So setting timescale to 0 would prevent execution of fixedUpdate, but it will also pause the entire physics simulation across your entire game, which I don't think is the desired behavior if I am interpreting your question correctly. I think this is a bit of an xy problem.

If you have code that you want to only execute if certain conditions are met you should use an if-statement. You mentioned in your question that an if-statement hadn't worked before, but this is its exact use case, and it should work if implemented properly. In this case you want to evaluate the "shouldExecute" boolean and then execute or not depending on the boolean value.

I would also recommend taking the code inside of fixed update and extracting it into another method to improve maintainability and modularity of the code.

Here is an example of how to implement the if-statement:

bool shouldExecute = false;

private void function setRandomColor(){
//.....Do stuff in here
console.log("setting random color");
}

private void FixedUpdate(){
if(shouldExecute == true){
setRandomColor();
}
}

private void OnMouseDown(){
// Mouse event has been changed to toggle the boolean rather than
// only turn it off
shouldExecute = !shouldExecute;
}

• this doesn't work – Laurenz Oct 4 '19 at 19:15

you just can put this before your code in FixedUpdate

if(Input.GetMouseButtonDown(0)) return;

• sorry this doesn't work – Laurenz Oct 4 '19 at 19:15
• @Laurenz 'This doesn't work' covers a LOT of ground. What do you mean by 'it doesn't work'? If you mean 'I'm seeing FixedUpdate() being called still' then that shouldn't be a surprise (and shouldn't be an issue); if you mean 'I'm seeing the spriteRenderer color being set still' then that's a different matter. This is a conceptually correct answer; to understand what's failing in practice needs much more information. – Steven Stadnicki Oct 4 '19 at 19:43