Godot: “无法添加子节点,已经有父节点”

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月24日 11:33:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定