Understanding PackedVector3Array references

Godot Version

4.3

Question

When trying to update the values contained within a PackedVector3Array, I was running into some weird behavior. I’m trying to update the vertex positions stored in an array before creating an array mesh.

This works:

for i in vertices.size():
	vertices[i].y = randf() * 10.0

But this doesn’t:

for vertex in vertices:
	vertex.y = randf() * 10.0

In my head, the two snippets would produce the same result. I was wondering if this is related to the note about packed arrays in the docs:

… To update a built-in property you need to modify the returned array, and then assign it to the property again.

Vector3 isn’t RefCounted, kind of a base-type like int, or float. It is copied instead of referenced when assigned to a new variable, including a for loop. Within the loop you are editing the copied vector, versus using a created int to edit the array.

for vertex: Vector3 in vertices: # copies the Vector3

for i: int in vertices.size():   # creates an int

A downside of automatically managed memory.

Ah that makes sense. I had been reading the notes scattered throughout the docs about this behavior for built-in types but wasn’t really sure how it applied, thank you

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.