#How to get children from a scene of a particular type

1 messages · Page 1 of 1 (latest)

fringe venture
#

There are two types of Objects in my scene.... Livingroom and Bedroom... I just want to get the children of Livingroom and Bedroom separately how to do that? get_children gets all child nodes regardless of types

hollow forge
#

Groups can be pretty useful for something like this. You can tag certain nodes as belonging to a certain group in the editor and then you can use the get_nodes_in_group() method to get just those ones. So you could have one group called "Livingroom" and another group called "Bedroom"

let me know if you have any questions about that 👍

#
var livingroom_nodes: Array = get_tree().get_nodes_in_group("livingroom")

could be an example

fringe venture
#

The Nodes are procedurally generated...

#

So how can I set the groups with code??

hollow forge
#

Great question! Luckily there is a handy little method that every Node has access to called 'add_to_group()'

the simplest way to use this method at runtime would be right after you generate your Node you could call

newly_created_node.add_to_group("livingroom")

While on the topic, it can be useful to know how to remove nodes from groups dynamically. This is accomplished with the "remove_from_group()" method.

node_i_want_to_remove.remove_from_group("bedroom")
fringe venture
#

Thank you!

hollow forge
#

Happy to help 🙇‍♂️

fringe venture
#

Its Not working

#

How to get all rooms in scene of certain group??

hollow forge
#

ah i think i see the issue

this line here

for room in $Rooms.get_nodes_in_group("LivingRoom")

The issue is that, as far as I can tell, $Rooms refers to a Node2D node. This type of node does not have the "get_nodes_in_group" method. That method belongs to the SceneTree object (which isn't even a node itself at all)

Luckily we can get our SceneTree Object easily with the method get_tree() (You may have seen this method used in some other areas of code before)

So what you really want is probably something more like this:

for room in get_tree().get_nodes_in_group("LivingRoom")

Just apply that same logic to your other lines as well and I think you will find success!