How to select and assign vertices to a vertex group via python? I have a script that generates random hair on sphere, and I want to make it work for a custom head mannequin, so I have to assign vertices to a vertex group for scalp hair, and then apply my script on it, so it adds hair only to the scalp part?
Considering you have access to an object, for instance:
obj = bpy.context.object
Then you can add a vertex group "Group", using:
group = obj.vertex_groups.new( name = 'Group' )
Or get an existing group by:
group = obj.vertex_groups['Group']
Then you can add vertices using:
group.add( vertex_indices, wanted_weight, 'REPLACE' )
where vertex_indices is an array of indices, wanted_weight the weight you want to assign. The last parameter ('type') corresponds to the operation you want ('REPLACE' to set the value, 'ADD' to add the value or 'SUBSTRACT').
The way you get the vertices is dependent of what you want to do.
If you have a vertex (from obj.data.vertices) you can get its index by:
From a vertex, you can get its assigned groups via:
This is an array of groups that you can use to check if the vertex is concerned by a group.
To obtain the assigned weight, from a given group and knowing a vertex index:
group.weight( vertex_index )