1
$\begingroup$

I'm trying to write something similar to the array modifier and am trying to modify the uvs of duplicated vertices, just like the modifier does, and add 1 on the X axis for every iteration. This code fails:

for i in range(8):
    bpy.ops.mesh.duplicate()
    bpy.ops.transform.shrink_fatten(value=-0.1, use_even_offset=False)

    for loop in ac_ob.data.loops:
        if actv_ob.data.vertices[loop.vertex_index].select is True:
            actv_ob.data.uv_layers.active.data[loop.index].uv += Vector([1, 0])

with the error:

ac_ob.data.uv_layers.active.data[loop.index].uv += Vector([1, 0])
IndexError: bpy_prop_collection[index]: index 0 out of range, size 0

location: <unknown location>:-1

The object does have a uv map. What am I doing wrong here?

$\endgroup$

1 Answer 1

1
$\begingroup$

Consider this shader, it uses the typical Array modifier $u$ coordinate offset of $1$ to make every 2nd element metallic:

Here's a Python script that efficiently duplicates the objects and for each removes the UV map, creates a new one, copies the data from the previous one, but increments the UV coordinates as specified in first two lines:

u_increment = 1.0
v_increment = 0.0

import bpy, numpy as np
from bpy import context as C

orig = C.object
offset = orig.dimensions[0]
uv_orig = orig.data.uv_layers['UVMap'].uv
size = len(uv_orig)
arr = np.empty(size*2, dtype=float)
uv_orig.foreach_get('vector', arr)

for i in range(4):
    ob = orig.copy()  # linked duplicate
    ob.data = ob.data.copy()  # need a copy to change UV
    ob.location.x += offset * (i+1)
    C.collection.objects.link(ob)
    uvs = ob.data.uv_layers
    uvs.remove(uvs[0])  # I don't understand why a new UV map has to be created
    uv_new = uvs.new()  # it seems like a mesh object reuses the copied UV otherwise
    arr.reshape((size,2))[:,:] += (u_increment, v_increment)
    uv_new.uv.foreach_set('vector', arr)

The front line is the Array modifier, and the next line is the effect of duplicating one Suzanne using the above script:

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .