How can i get true value of 'who_eat' from fruit.gd?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By diephuyduc

#Here is my fruit.gd code:
extends Area2D
signal fruit_eaten
export var who_eat = “who”
func _on_fruit_area_entered(area):
if(area.name == “head”):
who_eat = “snake”
queue_free()
emit_signal(“fruit_eaten”)
elif(area.name == “head1”):
who_eat = “snake1”
queue_free()
emit_signal(“fruit_eaten”)

And I use it in game.gd:

func spawn_next_fruit_and_tail():
var inst = fruit.instance()
var xx = get_random_number(900,50)
var yy= get_random_number(500,50)
inst.position = Vector2(xx, yy)
inst.connect(“fruit_eaten”, self, “spawn_next_fruit_and_tail”)
add_child(inst)
if inst.who_eat ==“snake”:
get_node(“snake”).add_tail()
elif(inst.who_eat == “snake1”):
get_node(“snake2”).add_tail1()
print(inst.who_eat)
#But it doesn’t work correctly.

:bust_in_silhouette: Reply From: njamster

But it doesn’t work correctly.

Obviously, otherwise you wouldn’t need to ask here. But what exactly did you expect and what happened instead? That’s the relevant information here!

One problem is that you’re storing the information about who ate a fruit in the fruit instance itself and then you queue_free that instance directly afterwards. Provide that information as an argument to the signal instead!

The other problem is that you don’t access the fruit that was just eaten, but the fruit that was newly instanced when calling `spawn_next_fruit_and_tail´.

This should work:

Area.gd

extends Area2D

signal fruit_eaten(by_whom)

func on_fruit_area_entered(area):
    if area.name == "head":
        emit_signal("fruit_eaten", "snake")
    elif area.name == "head1":
        emit_signal("fruit_eaten", "snake1")
    queue_free()

Game.gd

func spawn_next_fruit_and_tail(eaten_by):
    var inst = fruit.instance()
    var xx = get_random_number(900,50)
    var yy = get_random_number(500,50)
    inst.position = Vector2(xx, yy)
    inst.connect("fruit_eaten", self, "spawn_next_fruit_and_tail")
    add_child(inst)

    if eaten_by == "snake":
        get_node("snake").add_tail()
    elif eaten_by == "snake1":
        get_node("snake2").add_tail1()

When you post a question, please make sure that your code is formatted properly (each line has to start with 4 spaces, each additional 4 spaces equal an indentation layer). If you don’t, underscores are interpreted as markdown and indentation is lost, which makes your script a lot harder to read for others trying to help you.