How can i get true value of 'who_eat' from

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

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

And I use it in

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”)
if inst.who_eat ==“snake”:
elif(inst.who_eat == “snake1”):
#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:

extends Area2D

signal fruit_eaten(by_whom)

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

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")

    if eaten_by == "snake":
    elif eaten_by == "snake1":

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.