NodePath target as an instance variable

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

Hi there,

I’m new to godot and I’m trying to get a flexible way to make reusable scripts where one body can have multiple scripts. The best way I found was using NodePath to get the a target. It works when I’m using get_node() in the _physics_update() but not when I try to the get_node() in _ready() to attribue the value to an instance variable.

So this works:

extends Node

const UP=Vector2(0,-1)

export var speed=200
export var gravity=20
export var jump_strenght=500

export(NodePath) var target <=======================

var motion=Vector2()
var targetBody

func _physics_process(delta):
	targetBody=get_node(target)<=======================
	motion.y+=gravity

	if(Input.is_action_pressed("ui_right")):
		motion.x=speed
	elif(Input.is_action_pressed("ui_left")):
		motion.x=-speed
	else:
		motion.x=0

	if(targetBody.is_on_floor()):
		if Input.is_action_just_pressed("ui_up"):
			motion.y=-jump_strenght
	targetBody=targetBody.move_and_slide(motion,UP)
	pass

but this doesn’t :

extends Node

const UP=Vector2(0,-1)

export var speed=200
export var gravity=20
export var jump_strenght=500

export(NodePath) var target<=======================

var motion=Vector2()
var targetBody
func _ready():
	targetBody=get_node(target)<=======================
func _physics_process(delta):
	motion.y+=gravity

	if(Input.is_action_pressed("ui_right")):
		motion.x=speed
	elif(Input.is_action_pressed("ui_left")):
		motion.x=-speed
	else:
		motion.x=0

	if(targetBody.is_on_floor()):
		if Input.is_action_just_pressed("ui_up"):
			motion.y=-jump_strenght
	targetBody=targetBody.move_and_slide(motion,UP)
	pass

I got the following error :

Invalid call. Nonexistent function 'is_on_floor' in base 'Vector2'

when I log the targetBody I got a KinematicBody2D as I wanted so I can figure out why is it speaking about Vector2.

What’s wrong?

:bust_in_silhouette: Reply From: Zylann

Here is what’s wrong:

targetBody=targetBody.move_and_slide(motion,UP)

You overwrite your variable with a Vector2.