I’ve been trying to develop a code to create a material with specified color, based on the one shown here.
What I need is to create the material but, if it already exists, use the existing one (or override its color, ideally). I’ve created a Dynamo / Python routine for it, verifying the existence of the material with Dynamo and creating the material (or bypassing the existing ones) with Python. I must say that this is my first attempt at using Python or API related methods, so probably I’m missing something.
In Dynamo:
In Python:
# Código cópiado de Scott Crichton
import clr
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
def ToRevitColor(dynamoColor):
return Color(dynamoColor.Red, dynamoColor.Green, dynamoColor.Blue)
def ToDynamoObject(revitObject, isRevitOwned=False): # isRevitOwned should be False if Dynamo script created the object.
return revitObject.ToDSType(isRevitOwned)
doc = DocumentManager.Instance.CurrentDBDocument
names = IN[0]
transparencies = IN[1]
colors = IN[2]
run_bool = IN[3]
mat_exist = UnwrapElement(IN[4])
newMaterials = []
for test_bool in run_bool:
if test_bool == True:
for mat_name, transparency, color in zip(names, transparencies, colors):
TransactionManager.Instance.EnsureInTransaction(doc)
new_mat_id = Material.Create(doc, mat_name)
new_mat = doc.GetElement(new_mat_id)
new_mat.Color = ToRevitColor(color)
new_mat.Transparency = transparency
newMaterials.append(ToDynamoObject(new_mat))
TransactionManager.Instance.TransactionTaskDone()
else:
newMaterials.append(mat_exist)
OUT = newMaterials[0]
My problems are:
- The first run returns an error in the Python node, saying Exception: The given value for name is already in use as a material element name.Parameter name: name
- Despite the error message, the materials are created propperly, what makes me think somehow the Python scripts runs and reruns itself afterwards, finding the materials in the document, causing the error.
- The second time I hit run, the script runs without errors. The Python script returns the bypassed materials, read by the Dynamo nodes.
What am I missing? I think that maybe finding the existing materials (or their absence) directly in Python would make much more sense, but I couldn’t figure it out.