Setting Polygon2D UV coordinates in GDScript

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

Can UV coordinates of Polygon2D be changed in GDScript?

I tried and while I can set the polygon vertices, I cannot set UV coordinates.

I am doing this in an editor (3.0.6) tool script.


Doing this doesn’t change UV values in inspector.

Is this a bug?

mfabjan | 2018-10-12 06:36

:bust_in_silhouette: Reply From: bb_vb

(Answering old question because it still comes up on Google and it’s a useful question; this answer applies at least to version 3.3.3).

Like Polygon2D.polygon, it seems that Polygon2D.uv returns a copy of the array, not a reference. So calling uv.resize or uv.append only modifies the copy, not the underlying array, and therefore has no effect.

To actually set it, you need to assign the array directly:

poly.uv = PoolVector2Array([
	Vector2(0.0, 0.0),
	Vector2(0.0, 100.0),
	Vector2(100.0, 100.0),
	Vector2(100.0, 0.0),

The other thing to watch out for is that the UV coordinates here are specified in PIXELS, not [0,1] as used in a shader. If not specified, they appear to default to the same value as the vertex coordinates themselves (i.e., Polygon2D.uv == Polygon2D.polygon).
(Unfortunately none of this seems to be documented).

One last thing: you may need to restart the editor to make a “tool” script work.