With the following code

def weight_from_distance( scene ):
    floor = bpy.data.objects['GridGrass'] 
    cam   = bpy.data.objects['Camera']

    vert_distances = [ 
        ( cam.location - floor.matrix_world @ v.co ).length for v in floor.data.vertices 

    maxDist = max( vert_distances )
    minDist = min( vert_distances )

    for i, d in enumerate( vert_distances ):
        # Normalize distance and set as vertex weight
        floor.data.vertices[i].groups[0].weight = ( d - minDist ) / ( maxDist - minDist ) #Line 16

    pSysName      = 'ParticleSystem' 
    vertGroupName = 'GrassGrowth'

    floor.particle_systems[ pSysName ].vertex_group_density = vertGroupName # Update / Refresh

I get an error

enter image description here

Which seems to be saying that my mesh has no vertices, even though it is a huge terrain mesh with thousands of vertices?

Here's my terrain. It may be worth noting that it's a Grid.

enter image description here

  • $\begingroup$ Is your code actually indented like that, with the code at same level as the function definition? $\endgroup$ – Armored Wolf Jan 22 at 17:09
  • $\begingroup$ @ArmoredWolf I wish the solution was as easy as that but no, it just got changed when pasting. $\endgroup$ – Joehot200 Jan 23 at 12:10

A vertex has no vertex group.

Given the error is complaining that a collection does not have a single member (index 0) and the distances list is made from the vertices

floor.data.vertices[i].groups[0].weight = ( d - minDist ) / ( maxDist - minDist ) #Line 16

implies the error is that a vertex is assigned to no vertex group. Test for this.

if not floor.data.vertices[i].groups:

or ensure in some other way that all the vertices are assigned at least one group.

See second script in this answer re getting all the vertices in a group. Example below edited somewhat to match above

import bpy
from collections import defaultdict

scene = bpy.context.scene

vgs = defaultdict(list)
ob = scene.objects.get("GridGrass")
assert(ob is not None) # make sure it exists
me = ob.data
for v in me.vertices:
    for g in v.groups:

# print all verts in GrassGrowth vg

  • 1
    $\begingroup$ crap. Should have known I was being stupid. Super helpful answer, thank you :) $\endgroup$ – Joehot200 Jan 23 at 21:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.