Message 1 of 12
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
I want to paint 2 color alternate on every face of a solid3d object, im using Solid3d.SetSubentityMaterial method the code have no error but it won't work can anyone have me. Im using C#.net framework 4.8 at visual studio 2022. Here the code
public class Solid3dMaterialExample
{
[CommandMethod("SetTwoColorsToSolid3dFaces")]
public void SetTwoColorsToSolid3dFaces()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
// Select Solid3d object
PromptEntityOptions peo = new PromptEntityOptions("\nSelect a Solid3d:");
peo.SetRejectMessage("\nObject must be a Solid3d.");
peo.AddAllowedClass(typeof(Solid3d), true);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
{
ed.WriteMessage("\nNo valid Solid3d selected.");
return;
}
Solid3d solid3d = tr.GetObject(per.ObjectId, OpenMode.ForWrite) as Solid3d;
if (solid3d == null)
{
ed.WriteMessage("\nFailed to access Solid3d.");
return;
}
// Create two materials with different colors
ObjectId materialId1 = CreateMaterial(tr, db, "Material1", Color.FromColorIndex(ColorMethod.ByAci, 1)); // Red
ObjectId materialId2 = CreateMaterial(tr, db, "Material2", Color.FromColorIndex(ColorMethod.ByAci, 3)); // Blue
// Check and apply alternating materials to the faces
try
{
using (Brep brep = new Brep(solid3d))
{
int faceIndex = 0;
foreach (Autodesk.AutoCAD.BoundaryRepresentation.Face face in brep.Faces)
{
try
{
SubentityId faceId = face.SubentityPath.SubentId;
if (faceId.Type == SubentityType.Face) // Check the type of Subentity
{
// Apply alternating materials
ObjectId materialToApply = (faceIndex % 2 == 0) ? materialId1 : materialId2;
solid3d.SetSubentityMaterial(faceId, materialToApply);
ed.WriteMessage($"\nMaterial applied to face {faceIndex}.");
faceIndex++;
}
}
catch (System.Exception ex)
{
ed.WriteMessage($"\nError applying material to face: {ex.Message}");
}
}
}
}
catch (System.Exception ex)
{
ed.WriteMessage($"\nError processing Brep: {ex.Message}");
}
tr.Commit();
}
}
private ObjectId CreateMaterial(Transaction tr, Database db, string materialName, Color color)
{
// Create a new material
Material material = new Material
{
Name = materialName
};
// Add the material to the MaterialDictionary
DBDictionary materialDict = (DBDictionary)tr.GetObject(db.MaterialDictionaryId, OpenMode.ForWrite);
ObjectId materialId = materialDict.SetAt(materialName, material);
tr.AddNewlyCreatedDBObject(material, true);
return materialId;
}
}
Solved! Go to Solution.