How to enable and disable _process(delta) function?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ashish

I having trouble disabling the _process(delta) function.
I know that we have a method set_process(false), but somehow I am not able to disable the process(delta) function by calling this method from another function. Whatever function is being executed keeps getting executed over and over again despite a call to set_process(false) method. If I set an if condition and call this method within the if block, it doesn’t work, even when the if condition becomes true.
What am I doing wrong?
Can someone please give an example of how to enable and disable the _process(delta) function?

:bust_in_silhouette: Reply From: sash-rc

As you said yourself, set_process(false) is disabling virtual _process() function and should work very straightforward.
There could be a number of reasons why it is not working for you. Maybe you’re calling it for wrong node, maybe you’re not calling it at all.
But guessing is a wrong approach in programming. Use debugger to see what’s exactly going on. Post your code here (a minimal example that reproduces an issue).

:bust_in_silhouette: Reply From: jgodfrey

set_process() does work as intended. Here’s an example:

Create a new scene with this structure:

Node2D
    ButtonToggle (button node)

Attached the following script to the Node2D

extends Node2D

var time = 0

func _process(delta):
	time += delta
	print(time)

func _on_ButtonToggle_pressed():
	set_process(!is_processing())

Finally, wire the Button’s pressed() event to the script’s _on_ButtonToggle_pressed() handler.

Run the scene and note how pressing the button toggles the process state of the node and starts/stops executing the code in _process()

If it’s not working in your project, I’d say the problem is in your code. In that case, you’ll need to post the relevant code to get more assistance.