How can I read variables from another object?

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

Why doesn’t it work?

var enemy_lives = get_node("enemy2").lives
	if enemy_lives < 1:
		print("Hello")

Debugger:
Invalid operands ‘Nil’ and ‘int’ in operator ‘<’.

The script at enemy is:
var lives = 100

I look forward to any help.

Yes you can… i do it all the time.

make sure you spelled everything correctly and that the path to the enemy node is valid( the enemy_lives variable is in the parent node of the enemy node and that the path is indeed a valid one and that you get the enemy node by doing that

rustyStriker | 2018-02-10 16:11

It I’ve written everything right, but it still doesn’t work.

Flo | 2018-02-10 16:32

Example node hirarchy : Parent/Child/GrandChild

In GrandChild:

var life = 1.0

In Parent:

var grand_child_life = $Child/GrandChild.life
print(grand_child_life)
Output: 1.0

In Parent:

var armor = 2.0

In GrandChild:

var parent_armor = get_node("../..").armor
print(parent_armor)
Output: 2.0

This will always work with that particular hirarchy.

Footurist | 2018-02-10 16:42

Yes this works, but < does not work

Flo | 2018-02-10 16:52

Upload project file, I’ll give it a quick look.

Footurist | 2018-02-10 17:01

Another possibility is that you are doing both the initialization of the variable and the access to it inside the _ready functions of the objects. If this is the case, it is possible that the code assigning the value runs after the code that access it.

Artium Nihamkin | 2018-02-10 17:31

In the case of what Artium Nihamkin said, check your node hirarchy and make sure the node, that initializes the variable enters the scene tree first.

Footurist | 2018-02-10 18:17

Thank you for your help, I have solved the problem.

Flo | 2018-02-10 19:57