|
|
|
|
Attention |
Topic was automatically imported from the old Question2Answer platform. |
|
Asked By |
MightyRat |
I’ve made a golem spawn with this script:
extends Area2D
var spawn = false
export (int) var xLoc = -20
export (int) var yLoc = 0
export (int) var direction = -1
export (int) var time = 3
var enemy = preload("res://WarriorGolem.tscn")
func _physics_process(_delta):
var bodies = get_overlapping_bodies()
for body in bodies:
if body.name == "Player" && spawn == false: #error here!
spawn = true
var e = enemy.instance()
get_parent().add_child(e)
e.position = Vector2(xLoc, yLoc)
e.direction = direction
yield(get_tree().create_timer(time), "timeout")
spawn = false
if direction == 1:
$Sprite.flip_h = true
But it gives me that error: invalid get index ‘name’ (on base: ‘previously freed instance’)
|
|
|
|
Reply From: |
Magso |
At some point during the for loop, one or more of the bodies are being freed so when it comes back to body.name == "Player"
, body.name
can’t be found. If you’re trying to detect a single overlap by the player you’re better off using the body_entered
signal. The code can stay the same just without the need of a for loop.
What should I replace with body_entered?
MightyRat | 2020-05-30 08:43
extends Area2D
var spawn = false
export (int) var xLoc = -20
export (int) var yLoc = 0
export (int) var direction = -1
export (int) var time = 3
var enemy = preload("res://WarriorGolem.tscn")
func ready():
connect("body_enter", self, "on_GolemSpawner_body_entered")
func _on_GolemSpawner_body_entered(body):
if body.name == "Player" && spawn == false:
print("sciao")
spawn = true
var e = enemy.instance()
get_parent().add_child(e)
e.position = Vector2(xLoc, yLoc)
e.direction = direction
yield(get_tree().create_timer(time), "timeout")
spawn = false
if direction == 1:
$Sprite.flip_h = true
Now it works correcty! is the func ready that i’ve made correct?
The only problem is a bit of lag when a golem spawns, but it’s better than a crash I guess
MightyRat | 2020-05-30 09:08
Does it lag every time or only the first time it spawns? I’ve also had a slight lag issue on the first spawn, I don’t know if it’s instance()
, add_child()
or if it’s down to the parent node type of the instanced scene which for me was a CPUParticles node.
It is add child,when a golem spawns there s a little freeze(Not every time)
MightyRat | 2020-05-30 11:17