Godot Array copies by reference by default

If you are building reusable objects procedurally, and you are using array’s and the arrays are blank after the first “clear” of the array before you reuse it. You are probably copying the array content. Here’s an example of a copy.

	position_origin.append(upper_left_x);
	position_origin.append(upper_left_y);  
	print(position_origin);
	position_frame.append(position_origin);
	print(position_frame);
	position_origin.clear();
	print(position_origin);
	print(position_frame);

In the above example when you clear out position_origin array to reuse it for the next object, the contents in position_frame are cleared out. This is because the default copy of an array is a reference (or memory location) instead of a copy of the content in the array.

For this example, to work correctly, you have to use the duplicate() which compies the content of the array.

	position_origin.append(upper_right_x);
	position_origin.append(upper_right_y); 
	print(position_origin);
	position_frame.append(position_origin.duplicate()); 
	print(position_frame);
	position_origin.clear();
	print(position_origin);
	print(position_frame);