简体   繁体   中英

Rotate multiple elements in Revit with C#

I'm writing a Macro in Revit with C# for rotate multiple selected elements at a time. But I'm getting this error every time I try to run it: "System.NullReferenceException: Object Reference Not Set to an instance of an object". I don't know why I get this error since there are no "null" references in my selection. Does anybody know what is happening? This is the code snippet:

        //Get document
        UIDocument uidoc = this.Application.ActiveUIDocument;
        Document doc = uidoc.Document;

        //Elements selection
        double angle = 45.0;
        var elements = uidoc.Selection.PickObjects(ObjectType.Element,"Select Elements") as List<Element>;
        foreach (Element element in elements)
        {
            LocationPoint lp = element.Location as LocationPoint;
            XYZ ppt = new XYZ(lp.Point.X,lp.Point.Y,0);
            Line axis = Line.CreateBound(ppt, new XYZ(ppt.X,ppt.Y,ppt.Z+10.0));

            using(Transaction rotate = new Transaction(doc,"rotate elements"))
            {
                rotate.Start();
                ElementTransformUtils.RotateElement(doc,element.Id,axis,angle);
                rotate.Commit();
            }
        }

You are getting a NullReferenceException because the return type of PickObjects is IList<Reference> and not List<Element> .

Try something like this:

var elements = uidoc.Selection.PickObjects(ObjectType.Element, "Select Elements")
.Select(o => uidoc.Document.GetElement(o));

Consider also that the angle is measured in radians and not in degrees as you wrote, or at least i think you don't want to rotate the element 45 rad;).

Finally, do not forget that element.Location is not always a LocationPoint , depending on the selected element you could get a LocationPoint , LocationCurve or the base class ´Location´.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM