How to temporarily activate / deactivate nodes ... I am just making a game with multiple playable character.. For that I am keeping all the Playable characters in the single scene... and randomly select a Playable character and make all the other character nodes deactive.. So that the current Character node do not interact with the other nodes in the scene..
How to temporarily activate / deactivate nodes
The easiest way is to make the nodes invisible when you want them deactivated. This requires adding some additional if
checks, but it's fairly straight forward:
extends Node2D
func _process(delta):
if (visible == false):
return;
"Do whatever you would normally do here!"
The problem with this method is it does not work if you want invisible nodes that continue to work. You can get around that by making a boolean and using that instead to get around the visibility problem.
Regardless of whether you are using visible
or a additional boolean variable, any node with collision shapes will still be interactable. This means any StaticBody
, RigidBody
, KinematicBody
, and Area
nodes will still be intractable and in the way regardless of the fact that they are invisible and none of your code is running on them.
There are a couple ways to get around this too, but it makes the code interesting depending on how you want to go about it. I almost always do it one of the following two ways:
Disabling collision shapes:
extends KinematicBody2D
var active = false;
func _process(delta):
if (active == false):
return;
"do whatever you need to do..."
func activate():
get_node("CollisionShape2D").disabled = false;
visible = true;
func deactivate():
get_node("CollisionShape2D").disabled = true;
visible = false;
Change collision layers/masks to a unused layer/mask:
extends KinematicBody2D
var active = false;
var starting_layer = null
var starting_mask = null
func _ready():
starting_layer = collision_layer;
starting_mask = collision_mask;
func _process(delta):
if (active == false):
return;
"do whatever you need to do..."
func activate():
collision_layer = 0;
collision_mask = 0;
visible = true;
func deactivate():
collision_layer = starting_layer;
collision_mask = starting_mask;
visible = false;
That's how I primarily activate/deactivate nodes in my projects. :smile: