0

I am making a 2D platformer game in Godot, I create an object using the code:

if currentPlayers < playerLimit:
    var person = humanScene.instance()
    add_child(person)
    person.position = Vector2(90, 300)
    currentPlayers += 1
    print(person.position)

This works well, but in the "_physics_process(delta):" function, if i try doing:

    "print(person.position)"

it says:

"Invalid get index 'position' (on base: 'null instance')"

No matter what I try, my code can't seem to find the instanced object to find its position (i need its position every frame). Is there a special way to access instanced objects data (such as their positions?) thank you in advance!

chunkyPug
  • 3
  • 6

1 Answers1

1

This is an issue of scope. The variable person is defined only within the if, and is not available in _physics_process.

You'll want to first define the variable outside the limited scope, and then set its value inside the if. For example:

var person = null


func some_function_where_this_happens():
    if currentPlayers < playerLimit:
        person = humanScene.instance()
        add_child(person)
        person.position = Vector2(90, 300)
        currentPlayers += 1
        print(person.position)


func _physics_process(delta):
    print(person.position)

As it looks like your intention is to support multiple players, you'll probably want to switch the var person = null part for an array that holds all the players.

Eilam G
  • 58
  • 5