How to add material to an object if I know the material index?

Hi there,

I would like to add a material to an object by knowing the material index however I could not find the method. Only method I can use is the match material, but what if the object is being deleted before the I use it.

does this help ?

if not, you may want to post your code and the used programming language…
kind regards -tom

Hi @onrender,

Generally speaking, you’d do something like this:

var sphere = new Sphere(Plane.WorldXY, 5);
var attributes = doc.CreateDefaultAttributes();
attributes.MaterialSource = ObjectMaterialSource.MaterialFromObject;
attributes.MaterialIndex = material_index; //  your index...
doc.Objects.AddSphere(sphere, attributes);
doc.Views.Redraw();

– Dale

Thank you for the hint,

I have found some other methods that helped to achive what I wanted.

My first thought was that the Index is enough to pick up material ID but we need Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject as well.

One other question; What is the difference between the two line because I got error (expected attributes (4) get (3). when I used Rhino.DocObjects.Tables.ObjectTable.

attrChange = Rhino.DocObjects.Tables.ObjectTable.ModifyAttributes(objMat, attr, True)
attrChange = scriptcontext.doc.Objects.ModifyAttributes(objMat, attr, True)

Script:

import Rhino
import scriptcontext
import System.Drawing
import rhinoscriptsyntax as rs

def ChangeAttr():
    obj = rs.GetObject ( message=None, filter=0, preselect=False, select=False, custom_filter=None, subobjects=False)
    matIndex = rs.ObjectMaterialIndex (obj)
    rs.DeleteObject(obj)
    objMat = rs.GetObject ( message=None, filter=0, preselect=False, select=False, custom_filter=None, subobjects=False)
    attr = Rhino.DocObjects.ObjectAttributes()
    attr.MaterialIndex = matIndex
    attr.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject
    #attrChange = Rhino.DocObjects.Tables.ObjectTable.ModifyAttributes(objMat, attr, True)
    attrChange = scriptcontext.doc.Objects.ModifyAttributes(objMat, attr, True)
    scriptcontext.doc.Views.Redraw();

This:

attrChange = Rhino.DocObjects.Tables.ObjectTable.ModifyAttributes(objMat, attr, True)

is attempting to perform an operation on a non-existent object table.

This:

attrChange = scriptcontext.doc.Objects.ModifyAttributes(objMat, attr, True)

is performing an operation on the document’s object table

Hi Dave,

When I use the script it Ungroups the grouped objects? Is this a bug?

def ChangeMaterial(matIndex, ObjectID):
    attr = Rhino.DocObjects.ObjectAttributes()
    attr.MaterialIndex = matIndex
    attr.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject
    attrChange = scriptcontext.doc.Objects.ModifyAttributes(ObjectID, attr, True)
    scriptcontext.doc.Views.Redraw();

I created a new topic: Bug in object attributesin RhinoCommon