0 votes
asked Oct 12, 2019 in Engine by IndigoGames (69 points)
reshown Oct 13, 2019 by IndigoGames

1 Answer

+2 votes
Best answer

When you change a node type from the editor using Change Type, what the editor node is actually deleting your node, creating a new one, and somehow assign some of the properties they have in common.

This operation is not a light one, and information may be lost when you do this, so I'd advise you to consider alternatives before doing this at runtime in your game.

I'm not aware of a function in GDScript doing this, but the whole thing can be done with a few lines of code:

# Replacing a Sprite with an AnimatedSprite.
# I assume you have the `parent` node in a variable.
# -----------------

# Get the old node
var old_node = parent.get_node("TheSprite")

# Remove it from the tree
parent.remove_child(old_node)

# Destroy it (not immediately, some code might still use it)
parent.call_deferred("free")

# Create new node
var new_node = AnimatedSprite.new()

# Add the new node to the tree, under the same parent
parent.add_child(new_node)

# Move it to same order within children
parent.move_child(new_node, old_node.index)

# Set properties you want to be the same
new_node.name = old_node.name
new_node.position = old_node.position
new_node.rotation = old_node.rotation
new_node.scale = old_node.scale
# Etc...

There are variants of this, so you may want to change this code to suits your needs.

answered Oct 12, 2019 by Zylann (26,033 points)
selected Oct 13, 2019 by IndigoGames
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.