1
\$\begingroup\$

Godot v3.3.1.stable.mono.official


I am trying to draw a CollisionPolygon2D programmatically but I cannot resize or write the PoolVector2Array property called polygon:

extends CollisionPolygon2D func _ready() -> void: polygon.resize(1) print(polygon.size()) polygon[0] = Vector2.ZERO 

This code prints 0 and throws an error: Invalid set index '0' (on base: 'PoolVector2Array') with value of type 'Vector2'.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The type PoolVector2Array is a value type, and reading polygon gives you copy. Use another variable to hold it and edit it:

func _ready() -> void: var points = polygon points.resize(1) points[0] = Vector2.ZERO polygon = points print(polygon.size()) 

If you are going to build it over time, I suggest to add another field, and do the modifications to that field:

var _points := PoolVector2Array() func _ready() -> void: _points.resize(1) _points[0] = Vector2.ZERO polygon = _points print(polygon.size()) 

And you would be doing polygon = _points every time you need to commit the changes.

\$\endgroup\$
3
  • \$\begingroup\$ I cannot find any documentation on what a value type is. I guess CanvasItem.material is also a value type? When a property refers to a more complex object than built-in types it gives access to it by a copy? Maybe you can ask and answer a question about that? \$\endgroup\$ Commented May 24, 2021 at 8:15
  • \$\begingroup\$ @pietrodito Welcome to softwareengineering.stackexchange.com: Value/reference type, object and semantics. An abstract for this case would be that when you get some data, it might be a reference (think a wrapped pointer) to some instance, or it could be the instance. If you get the instance, it is a copy, any modifications on it are not reflected anywhere else. But if it is a reference to the instance, then you manipulating that instance that is stored somewhere else, so the changes are reflected. \$\endgroup\$ Commented May 24, 2021 at 8:43
  • \$\begingroup\$ @pietrodito I had a look at Material, and it appears to be a Reference type: docs.godotengine.org/en/stable/classes/class_material.html - It is not really about how complex it is, however the tendency is the opposite. The more complex a type is, the greater the incentive to pass references around instead of copies. However, in some cases GDScript may hide the fact that a copy happens, but not for these array types. I'm not sure how to phase the question (Edit: specific to Godot, of course) to answer that myself. \$\endgroup\$ Commented May 24, 2021 at 10:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.