英文:
Godot: "Can't add child, already has parent"
问题
在运行时,我收到消息“无法将TREE添加到Main3D,Main3D已经有父节点”。如何修复这个问题?
英文:
I am trying to spawn a bunch of trees in a 3d space randomly.
Code:
extends Spatial
var position = Vector3.ZERO
onready var tree = preload("res://TREE.tscn")
var tree_amount = 400
var tree_count = 0
var can_add_tree = true
func _ready():
randomize()
func _process(delta):
position.x = rand_range(-200, 200)
position.z = rand_range(-200, 200)
var new_tree = tree.instance()
if can_add_tree:
for i in range(tree_amount):
add_child(new_tree)
new_tree.set_global_translation(position)
tree_count += 1
if tree_count == tree_amount:
can_add_tree = false
However, when I run this it gives me the message "Can't add child TREE to Main3D, already has parent Main3D". How do I fix this?
答案1
得分: 1
使用这行代码创建一个新的树:
var new_tree = tree.instance()
使用这行代码将它添加到场景中:
add_child(new_tree)
问题在于你在循环中创建了一个新的树,并多次将其添加到场景中。
相反,应该在循环内部创建一个新的树,这样循环的每次迭代都会创建一个新的树。
附加信息: 你是不是想在每帧(每次 _process
运行时)都添加一个新的树?如果是这样,根本不需要使用循环。另一方面,如果你想在开始时创建这些树,你可能可以在 _ready
中运行这段代码。
英文:
With this line you create a new tree:
var new_tree = tree.instance()
With this line you add it to the scene:
add_child(new_tree)
The issue is that you are creating a single new tree and adding it to the scene multiple times in a loop.
Instead, create a new tree inside the loop. So each iteration of the loop is a new tree.
Addendum: Did you mean to add a new tree each frame (each time _process
runs)? In that case, don't do a loop at all. On the flip side, if you want to create the trees at the start, you probably can run the code in _ready
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论